Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ocaml

reason

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?

like image 532
Erik Avatar asked Dec 23 '22 03:12

Erik


1 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));
};
like image 195
shrynx Avatar answered Dec 25 '22 15:12

shrynx