functional programming - D-like slices of immutable data in OCaml -
does ocaml have slices (like d slices of immutable data)? seems fit nicely ocaml paradigm (you avoid having reverse list every time want kind of processing tail recursion, because can access/slice list both ends). difficult implement?
as example, if ocaml lists behaved slices, say
let merge lhs rhs = merge_helper lhs rhs [] let rec merge_helper lhs rhs res = match lhs | [] -> res ^ rhs | l_first :: l_rest -> match rhs | [] -> res ^ lhs | r_first :: r_rest -> if l_first <= r_first merge_helper l_rest rhs (res ^ [l_first]) else merge_helper lhs r_rest (res ^ [r_first])
where lhs ^ rhs attempts concatenate them copying rhs space next lhs (if available) , otherwise copies them new slot in memory @ least twice large lhs.
edit: perhaps need clarify concatenation such let concatted = lhs ^ rhs not mutating operation. lhs same was, , rhs same was. concatted may or may not point same segment of memory lhs (just larger length). copying talking "under-the-hood" operation. client's perspective objects behave if immutable , construction lhs ^ rhs takes amortized o(|rhs|) time (amortized in sense if keep on constructing longer slices repeatedly concatenating things on right, number of internal re-allocations small).
edit 2: sorry, imagining concatenating behaves d appending. d doesn't because allow slices of mutable data, in ocaml things default immutable, wouldn't problem (at least, no more d lists).
i think don't understand lists are. seem consider list c++ vector (i don't know d's slices have found, looks c++ vector) more restrictions.
it not! list immutable, persistent , gives constant time cons (::) , impossible achieve array (even smart array call slice).
example of thing can lists not arrays:
let l = [1; 2; 3; 4; 5] let = 0 :: l let b = 1 :: l
the last 2 lines constant time (no matter size of l
) , add constant space.
Comments
Post a Comment