Skip to content

Instantly share code, notes, and snippets.

@jeremyabbott
Last active December 2, 2016 21:52
Show Gist options
  • Save jeremyabbott/f7ae9303be8507f3935b41fcd4e7daa9 to your computer and use it in GitHub Desktop.
Save jeremyabbott/f7ae9303be8507f3935b41fcd4e7daa9 to your computer and use it in GitHub Desktop.
I think I get apply (finally)
(*
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
@cboudereau
Copy link

Yeah you got it!!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment