lambdaf#anonymous-functionpipelining

F# anonymous functions, pipelining


I am trying to understand lambda functions from the beginning of my f# course and still struggling to read and use them sometimes.

let wordCount = "aaa aaa".Split [| ' ' |]
wordCount.Length // 2
let letterCount = wordCount |> Array.sumBy (fun w -> w.Length) 

How I understand the lines above : The first two are straightforward, the third one is one that i dont understand. Since the wordCount is an array of strings [|"aaa"; "aaa"|], how does Array.sumBy (fun w -> w.Length) know that an array is passed as an argument and (fun w -> w.Length) just works properly. Does sumBy just executes the anon function on every element of array? Is this the same on .map and other such methods?

And also small question, difference btw >> and |>?


Solution

  • The |> operator, used as x |> f takes two arguments f and x. It then passes x to f as an argument, i.e. calling f x.

    This means that: wordCount |> Array.sumBy (fun w -> w.Length)
    Is the same as: Array.sumBy (fun w -> w.Length) wordCount

    Now, Array.sumBy f input is a function that applies f to all items from the input array input and sums the numbers returned for the individual elements.

    So, if you have: Array.sumBy (fun w -> w.Lenght) [| "aa"; "b" |]
    This is the same as ((fun w -> w.Lenght) "aa") + ((fun w -> w.Lenght) "b")
    Which is just: "aa".Length + "b".Length and that is 3.

    The function composition operator f >> g takes a function f and g and it produces a new function (fun x -> g (f x)) that takes an input, passes it to f and then passes the result of that to g.