I’m looking at the List documentation. It seems the library does not provide a sublist function.
I’m trying to get list of elements from i to j. Now I have to write it as:
let rec sublist list i j =
if i > j then
[]
else
(List.nth list i) :: (sublist list (i+1) j)
which is quite concise but I’m questioning the efficiency of List.nth, because if it’s O(n), I would rather have to write it in a less concise way.
I’m wondering why didn’t they provide List.sublist func, if List.nth is not O(1), because it’s such a quite common operation..
The above is more or less a deforested version of newacct’s solution. newacct’s solution allocates an intermediate list (
drop i list), which is possible for the compiler to optimize away in Haskell but much harder in ML. Therefore his version is perfectly fine for a Haskell function and marginally sub-optimal for an ML one. The difference between the two is only a constant factor: both are O(e). zrr’s version is O(length(l)) sinceList.filteridoesn’t know thatfonly returnsfalseafter a while, it calls it for all elements inl.I’m not very happy to let
bgo negative but the version where it doesn’t is more complicated.One reference among quite a few for deforestation if you’re interested: http://homepages.inf.ed.ac.uk/wadler/topics/deforestation.html