Created
March 28, 2021 14:00
-
-
Save y2kappa/e919be9d13ec42117b84bba6997ddaa5 to your computer and use it in GitHub Desktop.
OCaml piping
This file contains hidden or 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
type user = int | |
type task = { | |
desc: string; | |
priority: int; | |
is_finished: bool; | |
} | |
let to_string (t : task) : string = | |
Printf.sprintf | |
"Task { desc: %s; priority: %d; is_finished: %b" | |
t.desc | |
t.priority | |
t.is_finished | |
let get_user username password : user = 123 | |
let get_tasks user : task list = | |
ignore user; | |
[ | |
{desc = "Eat"; priority = 4; is_finished = false}; | |
{desc = "Sleep"; priority = 6; is_finished = false}; | |
{desc = "Study"; priority = 2; is_finished = false}; | |
{desc = "Read"; priority = 2; is_finished = false}; | |
{desc = "Pay bills"; priority = 3; is_finished = false}; | |
{desc = "Food shopping"; priority = 1; is_finished = false}; | |
] | |
let rec take n list = | |
(* tail call *) | |
let rec aux taken remaining n = | |
if n = 0 then taken else | |
match remaining with | |
| [] -> taken | |
| hd :: tl -> aux (hd::taken) tl (n-1) | |
in | |
aux [] list n | |
|> List.rev | |
let get_top_three_ user password = | |
let id = get_user user password in | |
let tasks = get_tasks id in | |
let outstanding = List.filter (fun t -> not t.is_finished) tasks in | |
let sorted = List.sort (fun t1 t2 -> if t1.priority > t2.priority then 1 else -1) outstanding in | |
let top_three = take 3 sorted in | |
top_three | |
let get_top_three user password = | |
get_user user password | |
|> get_tasks | |
|> List.filter (fun t -> not t.is_finished) | |
|> List.sort (fun t1 t2 -> if t1.priority > t2.priority then 1 else -1) | |
|> take 3 | |
let () = | |
get_top_three_ "user" "password" | |
|> List.map to_string | |
|> String.concat ", " | |
|> print_endline | |
let () = | |
get_top_three "user" "password" | |
|> List.map to_string | |
|> String.concat ", " | |
|> print_endline |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment