OCaml - splitting list into two separate, greater or lesser than given number -
OCaml - splitting list into two separate, greater or lesser than given number -
i have problem writing function result shown below:
split([7;1;4;3;6;8;2], 4) = ([1;3;2;4], [7;6;8])
my current code managed write:
let split(list, number)= allow split1(list, number, lesser, greater)= if list = [] lesser::greater else if list.hd list <= element (list.hd list)::(lesser) else (list.hd list)::(greater) in (list.tl lista, element, [], []);;
thanks in advance help.
for future, helps more specific when asking question on so. problem? users skeptical of wants others help them, won't help themselves.
your code has right structure, there few errors in there seem getting in way.
firstly lesser::greater
wrong, since left hand side of cons operator must list itself, want list both of these elements. instead seek [lesser;greater]
.
secondly, if think through code, notice stops. checked first element, didn't @ rest of list. since want maintain splitting list, need code maintain executing till end of list. accomplish this, utilize recursion. recursion mean function split1
phone call again. can confusing first time see - each time split1 runs take first element off, and split remainder of list.
what (list.hd list)::(lesser)
mean? lesser here means of lesser elements in rest of list. need maintain taking element out of list , putting in either lesser or greater.
finally avoid using list.hd excessively - neater find head , tail using pattern matching.
here's working version of code:
let split(list, number)= allow rec split1(list, number, lesser, greater)= match list | [] -> [list.rev lesser;list.rev greater] | head::tail -> match (head <= number) true -> split1(tail,number,head::lesser,greater) | false -> split1(tail,number,lesser,head::greater) in split1(list, number, [], []);; split([1;2;3;4;5],3);;
the split1 function takes elements off 1 @ time, , adds them lists.
list ocaml
Comments
Post a Comment