简体   繁体   中英

Applying Fold function in F#

 let list_min_fold = List.fold (fun acc -> List.min acc ) 0 lst
    printfn"Using regular List.fold function:\n      The minimum is: %A\n" 
       (list_min_fold)

When I execute my code this error displays: error FS0001: The type '('a -> 'b)' does not support the 'comparison' constraint. For example, it does not support the 'System.IComparable' interface

Why? Please help :(

Are you trying to find the smallest number in a list? If so, you need to use the min function (which takes just two arguments) rather than List.min (which takes a list of arguments):

To keep the code the most similar to your example, you can write (note also that starting with 0 is not going to work, so I used System.Int32.MaxValue instead):

let lst = [4;3;1;2;5;]
let list_min_fold = List.fold (fun acc -> min acc) System.Int32.MaxValue lst

It is also worth noting that the function you pass to fold takes two arguments - the state acc and the current value:

let list_min_fold = List.fold (fun acc v -> min acc v) System.Int32.MaxValue lst

But thanks to partial function application you can omit one of them (as you did), or both of them:

let list_min_fold = List.fold min System.Int32.MaxValue lst

as always Tomas answer is spot on so I have but a small remark:

as you probably saw it makes no sense to try to find the minimum of an empty list (so the function probably should be of type 'a option and when you have an non-empty list it's very easy to use List.reduce (which is basically just a fold for binary operations and min is a great candidate for such an operation):

let list_min xs = 
   match xs with 
   | [] -> None 
   | _  -> List.reduce min xs
           |> Some

this way you get:

> list_min [2;1;5;3];;
val it : int option = Some 1
> list_min [2;1;5;3;0];;
val it : int option = Some 0
> list_min ([] : int list);;
val it : int option = None

ok it's a fair point that the question was about fold - so if it has to be exactly List.fold you can of course do (as TheInnerLight remarked):

let list_min xs = 
   match xs with 
   | []      -> None 
   | (x::xs) -> List.fold min x xs
                |> Some

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM