Last active
July 27, 2018 18:26
-
-
Save fcallejon/c19c55e9933118af6427ef1770c1b3e8 to your computer and use it in GitHub Desktop.
Playing a bit with bindings, partial functions and composition
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
// Playing a bit with bindings, partial functions and composition | |
// REPL: https://repl.it/@FernandoCallejo/FSharp101-Binding | |
open System | |
// binding to a value | |
let toValue = 10 | |
// binding to a method using an specific overload | |
let toAMethod = String.Format : _ * _ -> _ | |
// create a method that calls the same overload | |
let aMethod format value = | |
String.Format(format, (Seq.toArray [|value|])) | |
let concat old toConcat = | |
String.Concat (old, toConcat) | |
// binding to another method | |
let toAnotherMethod = aMethod | |
// binding to a method using an specific overload and partial application | |
let toAMethodPartially = aMethod "FixedFormat {0}" | |
// recursive functions need the "rec" keyword | |
// try removing it the compiler will complain about "fibo" not being defined | |
let rec fibo num = | |
match num with | |
| 1 -> 1 | |
| 2 -> 1 | |
| c -> fibo (c - 1) + fibo (c - 2) | |
let formattedToValue = toAMethod ("Format toValue {0}", (Seq.toArray [|toValue|])) | |
printfn "%s" formattedToValue | |
let formattedToValue2 = toAnotherMethod "Format toValue {0}" toValue | |
printfn "%s" formattedToValue2 | |
let formattedToValue3 = toAMethodPartially toValue | |
printfn "%s" formattedToValue3 | |
// compose a new funcion with params (a:int) (b:string) | |
// that will format the int and concatenate the string | |
let composedMethod = toAMethodPartially >> concat | |
printfn "%s" (composedMethod toValue " end") | |
let fiboValue = fibo toValue | |
printfn "Result of 'fibo toValue' %i" fiboValue | |
// this is actually a comparison | |
// in f# you assign values to variables using "<-" | |
toValue = 20 |> ignore | |
// cant' assign a value default values are immutable | |
// to test the assignment go to line 6 and add "mutable" after "let" | |
// toValue <- 10 | |
printfn "value of toValue %i" toValue |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would be better to add
.fs
as the file extension so we get synthax coloration :)