Skip to content

Instantly share code, notes, and snippets.

@natalie-o-perret
Created June 20, 2020 01:24
Show Gist options
  • Save natalie-o-perret/96171ee3bf93e026c683ad4f62db1d63 to your computer and use it in GitHub Desktop.
Save natalie-o-perret/96171ee3bf93e026c683ad4f62db1d63 to your computer and use it in GitHub Desktop.
Cheap F# TypeClass Impl.
[|42; 42; 42|]
[42; 42; 42]
seq [42; 42; 42]
Some 42
Ok 42
// Inspired by: https://angrydexterous.github.io/typeclassish.html#/7
module TypeClass =
type Fmap = Fmap with
static member ($) (Fmap, x:_ array ) = fun f -> Array.map f x
static member ($) (Fmap, x:_ list ) = fun f -> List.map f x
static member ($) (Fmap, x:_ seq ) = fun f -> Seq.map f x
static member ($) (Fmap, x:_ option ) = fun f -> Option.map f x
static member ($) (Fmap, x:Result<_, _>) = fun f -> Result.map f x
let inline map f x = (Fmap $ x) f
let printn whatever =
printfn "%A" whatever
[<EntryPoint>]
let main _ =
TypeClass.map (fun _ -> 42) [| 1 .. 3 |] |> printn
TypeClass.map (fun _ -> 42) [ 1 .. 3 ] |> printn
TypeClass.map (fun _ -> 42) (seq { 1 .. 3 }) |> printn
TypeClass.map (fun _ -> 42) (Some 0) |> printn
TypeClass.map (fun _ -> 42) (Result<int32, string>.Ok 0) |> printn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment