Peter Aba
Peter Aba

Reputation: 63

Please explain what this Seq.map call will do in F#

I encountered the following line in exercism.io solution for F#, but I have issues grasping with the Seq.map part will do. (Probably obvious, but number is an integer here)

let numberSequence = number |> string |> Seq.map (float >> (-) 48.0 >> (-) 0.0)

Can someone shed light on this for me?

Upvotes: 3

Views: 68

Answers (1)

Gus
Gus

Reputation: 26174

I guess the function is something like:

let numberSequence number = number |> string |> Seq.map (float >> (-) 48.0 >> (-) 0.0)

then:

> numberSequence 654 ;;
val it : seq<float> = seq [6.0; 5.0; 4.0]

If so, what it does is:

number |> string Converts the number to a string

string |> Seq.map this could be tricky, a string implements IEnumerable, so it can be interpreted as a sequence of chars seq<char>. So here each char is "mapped" to a function.

Now let's have a look at the function, it turns out it's a composition of functions:

float converts the char to a float

(-) 48.0 it's like fun x -> 48. - x so it subtract the previous result to 48

(-) 0.0 Similarly subtract 0 to the previous result.

The function in the map part is trying to get the numerical value of the char. Seq.map applies that function to each element and construct a new sequence with each result.

As a side note, that function could have been easily written as:

let numberSequence number = number |> string |> Seq.map System.Char.GetNumericValue

Upvotes: 7

Related Questions