Why have the data parameter in F# to come last, like the following code snippet shows:
let startsWith lookFor (s:string) = s.StartsWith(lookFor)
let str1 =
"hello"
|> startsWith "h"
Why have the data parameter in F# to come last, like the following code snippet shows:
let startsWith lookFor (s:string) = s.StartsWith(lookFor)
let str1 =
"hello"
|> startsWith "h"
I think part of your answer is in your question. The |>
(forward pipe) operator lets you specify the last parameter to a function before you call it. If the parameters were in the opposite order, then that wouldn't work. The best examples of the power of this are with chaining of functions that operate on lists. Each function takes a list as its last parameter and returns a list that can be passed to the next function.
From http://www.tryfsharp.org/Learn/getting-started#chaining-functions:
[0..100] |> List.filter (fun x -> x % 2 = 0) |> List.map (fun x -> x * 2) |> List.sum
The
|>
operator allows you to reorder your code by specifying the last argument of a function before you call it. This example is functionally equivalent to the previous code, but it reads much more cleanly. First, it creates a list of numbers. Then, it pipes that list of numbers to filter out the odds. Next, it pipes that result toList.map
to double it. Finally, it pipes the doubled numbers toList.sum
to add them together. The Forward Pipe Operator reorganizes the function chain so that your code reads the way you think about the problem instead of forcing you to think inside out.
As mentioned in the comments there is also the concept of currying, but I don't think that is as easy to grasp as chaining functions.