Last active
December 2, 2016 21:52
-
-
Save jeremyabbott/f7ae9303be8507f3935b41fcd4e7daa9 to your computer and use it in GitHub Desktop.
I think I get apply (finally)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* | |
I think I understand apply! | |
Apply is a function that takes an elevated multi parameter functions and partially applies it for you. | |
*) | |
//For example: | |
// usage: printfn "%s" <| sayGood "morning" "Clément" | |
let sayGood = sprintf "Good %s %s" // string -> string -> string | |
let oSayGood = Some sayGood // (string -> string -> string) option | |
// how do I call this? | |
// (a -> b) option -> a option -> b option | |
let apply fOpt xOpt = | |
match fOpt, xOpt with | |
| Some f, Some x -> Some (f x) // Only passing a single argument to the function! | |
| _ -> None | |
// Using apply we can partially apply the multi-parameter function. | |
(* | |
Before we use apply, let's talk about the signature of apply… | |
We said we can use apply to call a wrapped multi-parameter function. | |
The signature of apply says that the first argument is (a -> b) option. | |
When looking at "a" and "b" it's easy to forget that functions can also be types. | |
"a" could but something like ( t -> u) and "b" could be (x -> y). | |
Now a -> b is (t -> u) -> ( x -> y) which is (t -> u -> x -> y). | |
So (a -> b) really does represent a multi parameter function! | |
Let's apply apply! | |
*) | |
let r = Some "morning" |> apply oSayGood // r is now (string -> string) option | |
let r' = Some "Clément" |> apply r // r' is string option or "Good morning Clément" | |
// apply is typically represented by the infix operator <*>. | |
// The function goes to the left of the operator and the argument goes on the right. | |
let (<*>) = apply | |
// Using the apply operator, we can more easily use our multi-parameter function: | |
let r'' = | |
oSayGood | |
<*> Some "morning" | |
<*> Some "Clément" | |
r' = r'' // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yeah you got it!!!!