OCaml Style for a function that merges two sorted lists into one sorted list -


i new ocaml , auditing class. have homework prompt reads: "merge xs ys takes 2 integer lists, each sorted in increasing order, , returns single merged list in sorted order."

i have written function works:

let rec merge xs ys = match xs   | [] -> ys   | hxs::txs -> if hxs <= (match ys     | [] -> hxs     | hys::tys -> hys)       hxs :: merge txs ys        else match ys       | [] -> xs       | hys::tys -> hys :: merge xs tys  in merge [-1;2;3;100] [-1;5;1001] ;; 

i know if code considered in acceptable ocaml style? want avoid forming bad habits. feels compositionaly dense, maybe that's because i'm still not used ocaml.

thanks.

i find hard follow if hxs <= (match ...), , it's difficult format nicely. write

 ...  let hys =    match ys    | [] -> hxs    | hys :: _ -> hys  in  if hxs < hys     hxs :: merge txs ys  ... 

however, think might better match both xs , ys @ same time:

let rec merge xs ys =    match xs, ys    | [], _ -> ys    | _, [] -> xs    | hx :: txs, hy :: tys ->        if hx < hy hx :: merge txs ys else hy :: merge xs tys 

i think captures symmetry of problem better.

i think it's when length of code matches simplicity of problem solves. merging simple state, , code shouldn't need long (it seems me).


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -