String to integer conversion

"Márton Sasvári (IJ/ETH)" Marton.Sasvari at ericsson.com
Tue Aug 23 22:13:51 PDT 2005


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

-------------- next part --------------

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