Question

i'm new to F# so please take it easy on me :)

I wish to convert a string to a list of ints, however, the code i've written returns a list of ints in their ASCII representation.

let input = "123456"
        |> Seq.map int
        |> Seq.map(fun(x) -> x * 2)

returns

    98 
    100 
    102 
    104 
    106 
    108

I can't seem to find an int.Parse alternative in F#. Any help would be great

Was it helpful?

Solution

Being a .NET language, you can use the Char.GetNumericValue method directly

open System

let input = "123456"
    |> Seq.map Char.GetNumericValue
    |> Seq.map(fun(x) -> x * 2)

EDIT: Apparently Int32.Parse does not accept a single Char. Updated my answer accordingly.

OTHER TIPS

Yet another way:

"123456"
|> Seq.map (string >> int)
|> Seq.map ((*) 2)

Whenever you need to map a set of characters to their integer index in an ordered set, you can simply subtract the index of the first value in the set (in this case '1'), and thus avoid any library functions:

"123456"
    |> Seq.map (fun c -> int c - int '1')
    |> Seq.map (fun(x) -> x * 2);;

val it : seq<int> = seq [0; 2; 4; 6; ...]

The second mapped function can also be made point-free as:

"123456"
    |> Seq.map (fun c -> int c - int '1')
    |> Seq.map ((*) 2);;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top