Skip to content

add ocaml to euclidean #11

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 17, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions chapters/fundamental_algorithms/euclidean_algorithm/euclidean.md
Original file line number Diff line number Diff line change
Expand Up @@ -331,3 +331,26 @@ fn main() {
println!("{}", chk2);
}
```

### OCaml

```ocaml
let rec euclid_mod a b =

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can also be written as

let rec euclid_mod a = function
  | 0 -> a
  | b -> euclid_mod b (a mod b)

This also looks more like the Haskell version that uses patterns directly in equations.

if b = 0 then
a
else
euclid_mod b (a mod b)

let rec euclid_sub a b =

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, I'd condense it a little bit since the body is so narrow:

let rec euclid_sub a b =
  if a = b then a
  else if a < b then euclid_sub a (b - a)
  else euclid_sub (a - b) b

if a = b then
a
else if a < b then
euclid_sub a (b - a)
else
euclid_sub (a - b) b

let chk1 = euclid_mod (64 * 67) (64 * 81)
let chk2 = euclid_sub (128 * 12) (128 * 77)
let () = print_string ((int_of_string chk1) ^ "\n")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can use print_endline to avoid manually adding newlines, use pipe-forward, and also sequence into a single expression, i.e.

let () =
  chk1 |> int_of_string |> print_endline;
  chk2 |> int_of_string |> print_endline

let () = print_string ((int_of_string chk2) ^ "\n")
```