Skip to content

Instantly share code, notes, and snippets.

@bkase
Created January 24, 2022 21:42
Show Gist options
  • Save bkase/455f1a3a3ffeb062a124e0f045a5c922 to your computer and use it in GitHub Desktop.
Save bkase/455f1a3a3ffeb062a124e0f045a5c922 to your computer and use it in GitHub Desktop.
Haskell-style applicative Fold in OCaml
module Fold = struct
module T = struct
type ('a, 'e) t = Fold : ('x -> 'e -> 'x) * 'x * ('x -> 'a) -> ('a, 'e) t
let make ~step ~init ~finish = Fold (step, init, finish)
let map =
`Custom
(fun (Fold (step, init, finish)) ~f ->
Fold (step, init, fun x -> finish x |> f))
let return a = Fold ((fun () _ -> ()), (), fun () -> a)
let apply (Fold (step1, init1, finish1)) (Fold (step2, init2, finish2)) =
let step (x1, x2) e = (step1 x1 e, step2 x2 e) in
let init = (init1, init2) in
let finish (x1, x2) = finish1 x1 (finish2 x2) in
Fold (step, init, finish)
end
include T
include Applicative.Make2 (T)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment