Skip to content

Instantly share code, notes, and snippets.

@jtpaasch
Created August 16, 2018 17:05
Show Gist options
  • Select an option

  • Save jtpaasch/4b8587ed5483bb4554e1943361db50a4 to your computer and use it in GitHub Desktop.

Select an option

Save jtpaasch/4b8587ed5483bb4554e1943361db50a4 to your computer and use it in GitHub Desktop.
Tutorial/cheat sheet for using Jane Street Core's Sequences.

Sequence (from Jane Street Core)

Suppose you have a list.

let x = ["a"; "b"; "c"];;

Convert it to a sequence:

let x_seq = Seq.of_list x;;

Get the next item:

let a = Seq.next x_seq;;

This returns Some (a, {b, c}). It's an option, whose value is a pair.

Unwrap the Some:

let b = Option.val_exn a;;

Get the first value:

let c = fst b;;

You can print it, since it's a string:

print_endline c;;

Get the second item from b, which is the rest of the sequence:

let d = snd b;;

Now you can get the next item from that:

let e = Seq.next d;;

Repeat the same process:

let f = Option.value_exn e;;
print_endline (fst f);;
let g = snd f;;

Now there's one more item in the sequence. Get it:

let h = Seq.next g;;

You can get the item and print it:

let i = Option.value_exn h;;
print_endline (fst i);;

Get the last item in the sequence:

let j = snd i;;

Get the next value now:

let k = Seq.next j;;

You have nothing now:

let l = Option.is_none k;;

Create a sequence of integers:

let a = Seq.init (fun n -> n);;

Take the first two from that sequence:

let b = Seq.take a 2;;

Take the head of the sequence:

let c = Seq.hd a;;

Take the tail of the sequence:

let d = Seq.tl a;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment