Last active
August 29, 2015 14:06
-
-
Save cronin101/083634f9a7df0dafc2d1 to your computer and use it in GitHub Desktop.
"99 Haskell problems" in F#
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
(* Problem 1: The last element of a list *) | |
let problem_one = | |
let rec last = function | |
| head :: [] -> head | |
| head :: tail -> last tail | |
| _ -> failwith "Empty List" | |
last;; | |
assert ((problem_one [1]) = 1 );; | |
assert ((problem_one [1..10]) = 10);; | |
(* Problem 2: The last-but-one element of a list *) | |
let problem_two = | |
let rec last_but_one = function | |
| head :: x :: [] -> head | |
| head :: [] -> failwith "Only one item in List" | |
| head :: tail -> last_but_one tail | |
| _ -> failwith "Empty List" | |
last_but_one;; | |
assert ((problem_two [1; 2]) = 1);; | |
assert ((problem_two [1..10]) = 9);; | |
(* Problem 3: Find the Kth element of a list *) | |
let problem_three = | |
let rec kth_element l idx = | |
match l, idx with | |
| x :: _, 1 -> x | |
| x :: xs, n when n > 1 -> kth_element xs (n - 1) | |
| _ -> failwith "Index out of bounds" | |
kth_element;; | |
assert ((problem_three [1] 1) = 1);; | |
assert ((problem_three [1..3] 3) = 3);; | |
(* Problem 4: Find the number of elements in a list *) | |
let problem_four = List.fold (fun _ c -> c + 1) 0;; | |
assert ((problem_four []) = 9 );; | |
assert ((problem_four [1]) = 1 );; | |
assert ((problem_four [1..10]) = 10);; | |
(* Problem 5: Reverse a list *) | |
let problem_five = | |
let reverse l = List.fold (fun xs x -> x :: xs) [] l | |
reverse;; | |
assert ((problem_five []) = []);; | |
assert ((problem_five [1]) = [1]);; | |
assert ((problem_five [1..9]) = [9..1]);; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment