Difference between fold and reduce?

前端 未结 4 834
囚心锁ツ
囚心锁ツ 2020-12-13 05:12

Trying to learn F# but got confused when trying to distinguish between fold and reduce. Fold seems to do the same thing but takes an extra parameter. Is there a legitimate r

4条回答
  •  Happy的楠姐
    2020-12-13 05:42

    fold is a much more valuable function than reduce. You can define many different functions in terms of fold.

    reduce is just a subset of fold.

    Definition of fold:

    let rec fold f v xs =
        match xs with 
        | [] -> v
        | (x::xs) -> f (x) (fold f v xs )
    

    Examples of functions defined in terms of fold:

    let sum xs = fold (fun x y -> x + y) 0 xs
    
    let product xs = fold (fun x y -> x * y) 1 xs
    
    let length xs = fold (fun _ y -> 1 + y) 0 xs
    
    let all p xs = fold (fun x y -> (p x) && y) true xs
    
    let reverse xs = fold (fun x y -> y @ [x]) [] xs
    
    let map f xs = fold (fun x y -> f x :: y) [] xs
    
    let append xs ys = fold (fun x y -> x :: y) [] [xs;ys]
    
    let any p xs = fold (fun x y -> (p x) || y) false xs 
    
    let filter p xs = 
        let func x y =
            match (p x) with
            | true -> x::y
            | _ -> y
        fold func [] xs
    

提交回复
热议问题