Skip to content

Instantly share code, notes, and snippets.

@akrisanov
Last active February 19, 2023 20:07
Show Gist options
  • Save akrisanov/d48ca3e383cdd5bc689ffc953e318fca to your computer and use it in GitHub Desktop.
Save akrisanov/d48ca3e383cdd5bc689ffc953e318fca to your computer and use it in GitHub Desktop.
OCaml From Very Beginning
let isvowel c =
c = 'a' || c = 'e' || c = 'i' || c = 'o' || c = 'u';;
let isconsonant c = not (isvowel c);;
let rec factorial n =
if n <= 0 then 1
else n * factorial (n - 1);;
let rec sum n =
if n = 1 then 1
else n + sum (n - 1);;
let rec power x n =
if n = 0 then x
else x * power x (n - 1);;
let rec factorial n =
match n with
1 -> 1
| _ -> n * factorial (n - 1);;
let isvowel c =
match c with
'a' | 'e' | 'i' | 'o' | 'u' -> true
| _ -> false;;
let rec gcd a b =
match b with
0 -> a
| _ -> gcd b (a mod b);;
let isnil l =
match l with
[] -> true
| _ -> false;;
let rec length l =
match l with
[] -> 0
| _ :: tail -> 1 + length tail;;
let rec sum l =
match l with
[] -> 0
| head :: tail -> head + sum tail;;
let rec length_inner l n =
match l with
[] -> n
| head :: tail -> length_inner tail (n + 1);;
let length l = length_inner l 0;;
let rec odd_elements l =
match l with
a::_::t -> a :: odd_elements t
| _ -> l;;
let rec append a b =
match a with
[] -> b
| h::t -> h :: append t b;;
let rec rev l =
match l with
[] -> []
| h::t -> rev t @ [h];;
let rec take n l =
if n = 0 then [] else
match l with
h::t -> h :: take (n - 1) t;;
let rec drop n l =
if n = 0 then l else
match l with
h::t -> drop (n - 1) t;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment