How do you take a slice of a list in OCaml/ReasonML?

Viewed 2495

For example in Ruby you could do something like:

list = ["foo", "bar", "baz", "qux", "quux", "corge"]
result = list[2..4]

And result would contain ["baz", "qux", "quux"].

How would you do this in OCaml/ReasonML?

5 Answers

There is no in built function for slicing list, but can be done easily. Since we have a start point and an end point, we can break down the problem in two parts. First part is to drop a few elements till we reach the starting point and second part is to take few elements from the start point till the end point.

let rec drop = (n, list) =>
  switch (list) {
  | [] => []
  | [_, ...xs] as z => n == 0 ? z : drop(n - 1, xs)
  };

let rec take = (n, list) =>
  switch (list) {
  | [] => []
  | [x, ...xs] => n == 0 ? [] : [x, ...take(n - 1, xs)]
  };

now that we have these two functions, we can combine them to drop initial elements from till start point drop(i, list) and then pass this new list to take elements from start point to end point

take(k - i + 1, drop(i, list));

in total

let slice = (list, i, k) => {

  let rec drop = (n, list) =>
    switch (list) {
    | [] => []
    | [_, ...xs] as z => n == 0 ? z : drop(n - 1, xs)
    };

  let rec take = (n, list) =>
    switch (list) {
    | [] => []
    | [x, ...xs] => n == 0 ? [] : [x, ...take(n - 1, xs)]
    };

  take(k - i + 1, drop(i, list));
};

A better approach would be to provide starting point and then range rather than end point because here we don't constraint that end point should be bigger than starting point

let slice = (list, start, range) => {

  let rec drop = (n, list) =>
    switch (list) {
    | [] => []
    | [_, ...xs] as z => n == 0 ? z : drop(n - 1, xs)
    };

  let rec take = (n, list) =>
    switch (list) {
    | [] => []
    | [x, ...xs] => n == 0 ? [] : [x, ...take(n - 1, xs)]
    };

  take(range, drop(start, list));
};

If you have access to bucklescript's Belt libraries, you could do something like:

open Belt;

let myList = ["first", "second", "third", "fourth", "fifth", "sixth"];

/* To get 2..4 */
myList
  ->List.drop(2)
  ->Option.getWithDefault([])
  ->List.take(3)
  ->Option.getWithDefault([])
  ->Js.log;

/* Gives you the list ["third", "fourth", "fifth"] */

If you have access to BuckleScript, you can use:

let list = ["foo", "bar", "baz", "qux", "quux", "corge"];

let sliced = Js.Array.slice(~start=2, ~end_=4, list);

See more in the BuckleScript docs

Use

List.filteri (fun i _ -> i >= start && i <= end)
Related