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 |>?
The
|>operator, used asx |> ftakes two argumentsfandx. It then passesxtofas an argument, i.e. callingf x.This means that:
wordCount |> Array.sumBy (fun w -> w.Length)Is the same as:
Array.sumBy (fun w -> w.Length) wordCountNow,
Array.sumBy f inputis a function that appliesfto all items from the input arrayinputand 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".Lengthand that is3.The function composition operator
f >> gtakes a functionfandgand it produces a new function(fun x -> g (f x))that takes an input, passes it tofand then passes the result of that tog.