(Integer readFrom: 'abc' readStream) = 0

Paolo Bonzini bonzini at gnu.org
Thu Jan 10 07:37:53 UTC 2008


Zulq Alam wrote:
> Thanks Damien.
> 
> That's almost what I need, except '123abc' = 123 and '1.1' = 1, etc. I 
> think I want something more like this:
> 
> parseString: aString base: aBase ifFail: failBlock
>     " Answer a new integer described by the whole string aString in
>     base aBase. If the parse fails, return the value of the block
>     failBlock."
>     
>     | stream integer |
>     stream := aString readStream.
>     integer := (SqNumberParser on: stream)
>         nextIntegerBase: aBase
>         ifFail: [^ failBlock value].
>     stream atEnd ifFalse: [^ failBlock value].
>     ^ integer
> 
> parseString: aString ifFail: failBlock
>     " Answer a new integer described by the whole string aString in
>     base 10. If the parse fails, return the value of the block
>     failBlock."
>     
>     ^ self parseString: aString base: 10 ifFail: failBlock
> 
> Integer parseString: 'abc' ifFail: [#error]     "#error"
> Integer parseString: '123' ifFail: [#error]     "123"
> Integer parseString: '123abc' ifFail: [#error]. "#error"
> Integer parseString: '1.1' ifFail: [#error].    "#error"
> Integer parseString: '' ifFail: [#error]     "#error"

Or:

parseString: aString base: aBase ifFail: failBlock
     " Answer a new integer described by the whole string aString in
     base aBase. If the parse fails, return the value of the block
     failBlock."

     | stream integer |
     stream := aString readStream.
     integer := (SqNumberParser on: stream)
         nextIntegerBase: aBase
         ifFail: [ failBlock value: nil].

     "Pass partial value to failBlock"
     stream atEnd ifFalse: [failBlock value: integer].
     ^ integer

Paolo



More information about the Squeak-dev mailing list