String to integer conversion
Lee Salzman
lsalzman1 at cox.net
Tue Aug 23 23:32:51 PDT 2005
I committed the following:
s@(String traits) as: i@(Integer traits) &radix: radix
"Reads a radix-(10) Integer from the string."
[
(s isNotEmpty /\ [s first = $-])
ifTrue:
[^ ((s copyFrom: 1) as: i &radix: radix) negated].
radix ifNil: [radix: 10].
s inject: 0 into:
[| :n :c | (c isDigit: radix) ifFalse: [^ n].
n * radix + (c toDigit: radix)]
].
Although, this may be better off just using the lexer or Number
readFrom: String.
Lee
Márton Sasvári (IJ/ETH) wrote:
> Hi,
>
> The #as: method converting Strings to Integers does not work on negative
> values (returns zero) as the characters of the string are checked to be
> digits and the minus sign isn't one. I've attached three method versions
> working correctly not being able to descide which is the slate-iest in
> style.
>
> Regards,
> Marton
>
>
> ------------------------------------------------------------------------
>
>
> s@(String traits) as: _@(Integer traits) &radix: radix
> [
> s size = 0 ifTrue: [^ 0].
> radix ifNil: [radix: 10].
> (s at: 0) = $-
> ifTrue: [
> (s sliceFrom: 1) inject: 0 into:
> [| :n :c | (c isDigit: radix) ifFalse: [^ n].
> n * radix - (c toDigit: radix)]]
> ifFalse: [s inject: 0 into:
> [| :n :c | (c isDigit: radix) ifFalse: [^ n].
> n * radix + (c toDigit: radix)]]
> ].
>
> s@(String traits) as: _@(Integer traits) &radix: radix
> [| answer |
> radix ifNil: [radix: 10].
> answer: 0.
> s size > 0 ifTrue: [| negate start |
> (s at: 0) = $-
> ifTrue: [negate: True. start: 1]
> ifFalse: [negate: False. start: 0].
> start below: s size do: [| :i c |
> c: (s at: i).
> (c isDigit: radix) ifFalse: [^ answer].
> answer: answer * radix + (c toDigit: radix)].
> negate ifTrue: [answer: answer * -1]].
> answer
> ].
>
> s@(String traits) as: _@(Integer traits) &radix: radix
> [| op digits |
> s size = 0 ifTrue: [^ 0].
> radix ifNil: [radix: 10].
> (s at: 0) = $-
> ifTrue: [op: #-. digits: (s sliceFrom: 1)]
> ifFalse: [op: #+. digits: s].
> digits inject: 0 into:
> [| :n :c | (c isDigit: radix) ifFalse: [^ n].
> op sendWith: n * radix with: (c toDigit: radix)]
> ].
>
More information about the Slate
mailing list