- Commit
- be2c5ab39ecf02aeb341a34d63941832e26f8a58
- Parent
- 7dd0c20fc9a5d7887dd1b107cf6254edba09344f
- Author
- Pablo <pablo-escobar@riseup.net>
- Date
Replaced nested expressions with the |> operator
A OCaml module for manipulating unlimited register machines
Replaced nested expressions with the |> operator
2 files changed, 30 insertions, 21 deletions
diff --git a/main.ml b/main.ml @@ -9,7 +9,8 @@ let default_max_iters = 1000 (** An equivalent to Haskell's [sequence] *) let seq (xs : 'a option list) : 'a list option = let f x acc = - Option.join (Option.map (fun y -> Option.map (fun ys -> y :: ys) acc) x) + x |> Option.map (fun y -> Option.map (fun ys -> y :: ys) acc) + |> Option.join in List.fold_right f xs (Some []) @@ -19,20 +20,21 @@ let main iters regs file = let contents = really_input_string file (in_channel_length file) in try let program = Urm.parse contents - and regs_fn = (fun i -> if i < Array.length regs then regs.(i) else 0) in - match Urm.nexec iters program (Urm.of_registers regs_fn) with - | Some m -> - let regs_strs = - List.map - (Printf.sprintf "%d") - (List.init (Array.length regs) (Urm.register m)) - in Printf.printf "%s\n" (String.concat " " regs_strs) - | None -> - Printf.eprintf - "ERROR: the input program did not halt after %d iterations\n" - iters; - Printf.eprintf "The input program may not halt\n"; - exit 1 + and regs_fn i = if i < Array.length regs then regs.(i) else 0 + in + match Urm.nexec iters program (Urm.of_registers regs_fn) with + | Some m -> + let regs_strs = + Urm.register m + |> List.init (Array.length regs) + |> List.map (Printf.sprintf "%d") + in Printf.printf "%s\n" (String.concat " " regs_strs) + | None -> + Printf.eprintf + "ERROR: the input program did not halt after %d iterations\n" + iters; + Printf.eprintf "The input program may not halt\n"; + exit 1 with Urm.Syntax_error err -> Printf.eprintf "ERROR: %s\n" err
diff --git a/urm.ml b/urm.ml @@ -100,10 +100,17 @@ let parse_instruction (i : token list) : instruction = let parse (s : string) : instruction array = let f s = - match String.trim s with - | "" -> - None - | t -> - Some (parse_instruction (Stream.npeek 8 (lex (Stream.of_string t)))) - in Array.of_list (List.filter_map f (String.split_on_char '\n' s)) + if "" = String.trim s + then None + else + s |> String.trim + |> Stream.of_string + |> lex + |> Stream.npeek 8 + |> parse_instruction + |> Option.some + in + s |> String.split_on_char '\n' + |> List.filter_map f + |> Array.of_list