Skip to content

Instantly share code, notes, and snippets.

@ElectricCoffee
Last active January 25, 2022 23:20
Show Gist options
  • Select an option

  • Save ElectricCoffee/78cbbd6e6480e461484bed6360ecff71 to your computer and use it in GitHub Desktop.

Select an option

Save ElectricCoffee/78cbbd6e6480e461484bed6360ecff71 to your computer and use it in GitHub Desktop.
Fischer Random Chess setup generator written in OCaml
(** s combinator *)
let (<*>) f g x = g (f x) x;;
(** b combinator, i.e. function composition *)
let (<$>) f g x = x |> f |> g;;
(** replaces a single element in a list at index `pos` *)
let amend a pos lst = List.mapi (fun i x -> if i = pos then a else x) lst;;
(** picks a random item from a list *)
let pick lst =
let len = List.length lst in
let i = Random.int len in
List.nth lst i;;
(** get the indices of all the elements that match the input `what` *)
let get_indices what where =
List.mapi (fun i x -> (i, x)) where
|> List.filter (fun (_, x) -> x = what)
|> List.map (fun (i, _) -> i);;
(** the blank board *)
let board = Array.to_list(Array.make 8 ' ');;
(** random starting position for the white bishop *)
let white_bishop = pick [1; 3; 5; 7] |> amend 'b';;
(** random starting position for the black bishop *)
let black_bishop = pick [0; 2; 4; 6] |> amend 'b';;
(** random starting position for the knight *)
let knight = ((get_indices ' ') <$> pick) <*> (amend 'n');;
(** random starting position for the queen *)
let queen = ((get_indices ' ') <$> pick) <*> (amend 'q');;
(** fill out the three remaining spaces with the two rooks and the king *)
let rooks_and_king board =
match get_indices ' ' board with
| [r1;k;r2] -> board |> amend 'r' r1 |> amend 'k' k |> amend 'r' r2
| _ -> raise (Failure "The remaining empty spaces must be exactly 3 long");;
(** because ocaml doesn't already have this... *)
let char_list_to_string = (List.map (Printf.sprintf "%c")) <$> (String.concat "");;
(** chain it all together *)
board |> white_bishop |> black_bishop |> knight |> knight |> queen |> rooks_and_king |> char_list_to_string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment