Skip to content

Instantly share code, notes, and snippets.

@iArnold
Created June 17, 2015 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iArnold/d414bbbbc5c3e72fbf6e to your computer and use it in GitHub Desktop.
Save iArnold/d414bbbbc5c3e72fbf6e to your computer and use it in GitHub Desktop.
string-to-integer convertion
string-to-integer: function [
input [string!]
return: [integer! none!]
/local
total [integer!]
in-char [char! string!]
cipher [integer!]
is-number [logic!]
][
is-number: false
total: 0
forall input [
if is-number [
in-char: first input
cipher: switch/default in-char [
#"1" [1]
#"2" [2]
#"3" [3]
#"4" [4]
#"5" [5]
#"6" [6]
#"7" [7]
#"8" [8]
#"9" [9]
#"0" [0]
][
none!
]
either none! = type? cipher [
is-number: false
][
total: total * 10 + cipher
]
]
]
return either is-number [ total ][ none! ]
]
@Zamlox
Copy link

Zamlox commented Apr 6, 2016

Few optimizations:

string-to-integer: function [
    input [string!]
    return: [integer! none!]
    /local
    total [integer!]
    cipher [integer!]
][
    if empty? input [return none]
    total: 0
    forall input [
        cipher: switch/default first input [
                    #"1" [1]
                    #"2" [2]
                    #"3" [3]
                    #"4" [4]
                    #"5" [5]
                    #"6" [6]
                    #"7" [7]
                    #"8" [8]
                    #"9" [9]
                    #"0" [0]
                ][
                    return none
                ]
        total: total * 10 + cipher
    ]
    total
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment