Sorted Sublist within a F# list of integers

Viewed 68

I am trying to get a sublist which contains the largest and then eventually second largest element from left to right in F#. For example if I have list1 = [2;5;3;4] I should be able to get [5;4] as a result. list1 = [2;1;3;4] would be [4] and so on. I can't really thing of a clever way to do this. I got following lines:

let rec top<'a when 'a: comparison> (xs: List<'a>): List<'a> =
     match xs with
        | [] -> invalidArg "xs" "Empty list"
        | [x] -> x::xs
        | x1::x2::xs' -> top((max x1 x2)::xs')

which gives me [5;5] instead of [5;4]

I would really appreciate your help. Thanks

1 Answers

You can do it using an auxiliary recursive function.

let top list =
    let rec loop n = function
        | [] -> [n]
        | [x] -> if n < x then [x] else  [n; x]
        | x :: xs -> loop (max n x) xs
    match list with
    | [] -> invalidArg "list" "Empty list" 
    | x :: xs -> loop x xs

or using list.fold

let top (list: int list): int list =
    List.fold (fun s x -> if s.Head < x then [x] else [s.Head; x])
              [list.Head] 
              list.Tail
Related