문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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);;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top