Thomas
Thomas

Reputation: 12107

List.map with two function parameters, in F#

I came across this syntax:

[10.; 11.; 12.]
|> List.map (fun a b -> a * b)

in what case does List.map have two parameters (fun a b)?

This is the output in Jupyter Lab:

enter image description here

Upvotes: 1

Views: 315

Answers (1)

scrwtp
scrwtp

Reputation: 13577

That's a fun example, because it looks confusing and usually doesn't come up in practice, so it caught me off-guard initially.

In short, what happens is you're mapping a list of floats into a list of float -> float functions. It's easier to see if you rewrite it as something like this:

let results = 
    [10.; 11.; 12.]
    |> List.map (fun a -> (fun b -> a * b))

You pass a float -> float -> float function as the mapper, and it gets partially applied to the element from the input list. The second argument b is not being applied though, so the output of the mapping is a function that takes a float and multiplies it by the partially applied element of the list, and the overall result is a list of float -> float functions.

You can then apply those functions to some value like this:

results
|> List.map (fun f -> f 2.)

Upvotes: 2

Related Questions