I have to transform a list into a list, where the odds come first and evens after. I have the logic around it but am unsure how to write the code correctly.
The list should be split into 2 lists, one of all odds and one of all evens. Then join the evens to the odds with odds @ evens and output the final list. My code currently is :
let oddfirst = isOdd @ isEven;;
let isOdd list= List.allOdd (fun x -> x mod 2!= 0) list;;
let isEven list= List.allEven (fun y -> y mod 2= 0) list;;
CodePudding user response:
OCaml files are read top to bottom. You are concatenating two elements that are not defined. isOdd
and isEven
are not lists, they're functions that take int list
and return I don't know what since you're using functions that don't exist in the List
module.
Your code should look like:
let oddfirst l =
let isOdd = List.<find_the_function> (fun x -> x mod 2 <> 0) l in
let isEven = List.<find_the_function> (fun x -> x mod 2 = 0) l in
isOdd @ isEven
CodePudding user response:
The simplest way is to use the List.partition
function:
let oddFirst l =
let (even, odd ) = List.partition (fun x -> x mod 2 = 0) l in
odd @ even;;
oddFirst list
CodePudding user response:
Ok so i found out List.filter works best for me. Here is the solution:
let oddfirst l =
let isOdd = List.filter (fun x -> x mod 2 != 0) l in
let isEven = List.filter (fun x -> x mod 2 = 0) l in
isOdd @ isEven