The objective is very simple: I want to give an exact definition – by example – of the functional programming approach in code development.
I’ll use the idiomatic syntax of F# and I’ll assume we want to make a logger for any sort of array.
We want to abstract out the type of the results when we write a code to collect them. This is the only real world principle of functional programming. If you like the
for/foreach/while loop syntax, just use the nice C# language, no worries. But – in that case – don’t talk about idiomatic F# please. Thank you!
The logger – simple version
Ok, so we have a basic understanding of the development guidelines and we can express the main idea of a method, which will help us debugging our code.
let logFile path res = use sw = new StreamWriter(path, false) res |> Array.iter (fprintfn sw "%A")
Not bad. Bat we can go further into the abstraction.
The logger – advanced version
Look, there are 3 parts:
- we open a context
- we iterate a delegate on the array
- we close the above said context
let log (env: unit->'ctx) (fn: 'ctx -> 'a -> unit) (a: 'a array) (exit: 'ctx -> unit) = let ctx = env() a |> Array.iter (fn ctx) exit ctx
let logFile path a = log (fun () -> new StreamWriter(path, false)) (fun sw i -> fprintfn sw "%A" i) a (fun sw -> sw.Close() sw.Dispose())
Usage – that simple
anyArray |> logFile "anyArray.txt"
Yes, awesome indeed.