Last active
May 11, 2016 08:22
-
-
Save keleshev/c947198f482ba90e0a26 to your computer and use it in GitHub Desktop.
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
open Core_kernel.Std | |
module Pair = Tuple2 | |
let (>>) f g x = g (f x) | |
let (<<) f g x = f (g x) | |
module Hamming = struct | |
(* 1 no-dependencies *) | |
let rec distance ?(accu=0) left right = | |
match left, right with | |
| left_head :: left_tail, right_head :: right_tail -> | |
if left_head <> right_head then | |
distance ~accu:(accu + 1) left_tail right_tail | |
else | |
distance ~accu left_tail right_tail | |
| [], [] -> Some accu | |
| _ -> None | |
(* 2 lambda *) | |
let distance left right = | |
Option.map (List.zip left right) (List.count ~f:(fun (l, r) -> l <> r)) | |
(* 3 uncurry *) | |
let distance left right = | |
Option.map (List.zip left right) (List.count ~f:(Pair.uncurry (<>))) | |
(* 4 point-free *) | |
let distance = | |
List.zip >> (<<) (Option.map ~f:(List.count ~f:(Pair.uncurry (<>)))) | |
end | |
let () = | |
assert (Hamming.distance [1;2;3] [1;0;3] = Some 1); | |
assert (Hamming.distance [1;2;3] [1;2;3] = Some 0); | |
assert (Hamming.distance [1;2;3] [1;2; ] = None); | |
print_endline "ok" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment