Quantcast
Channel: Active questions tagged ocaml - Stack Overflow
Viewing all articles
Browse latest Browse all 531

Getting the two minimum values from a list in OCaml

$
0
0

I need to write a function twoMin: int list → int * int using foldl that returns the two smallest values (not elements) of a list. You may assume that the list contains at least two elements with different values.

let rec foldl f l acc = match l with  | [] -> acc  | x :: xs -> foldl f xs (f x acc)let twoMin lst =  match lst with  | [] | [_] -> failwith "List must contain at least two elements with different values."   | x :: y :: rest ->    let initial_acc = if x < y then (x, y) else (y, x) in    let (min1, min2) = foldl (fun a b -> if b < fst a then (b, fst a) else if b < snd a then (fst a, b) else a) rest initial_acc in    (min1, min2)

I keep getting error and I do not know what is wrong with the code.


Viewing all articles
Browse latest Browse all 531

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>