开发者

F# -> Fold with 2 parameters

I'm trying to make a custom fold w开发者_开发百科hich goes through my sequence, and takes 2 Teams a time and assign them to a Match and then return a Match list in the end.

My current code is:

let myFold f s =
    let rec myFold' f s acc =
        match s with
        | (a1::a2::a) -> f a1 a2::acc
        | _ -> acc
    myFold' f s []

Which gives me (int -> int) list

But obviously thats not going to work... What am I doing wrong? -> I know that I just can create a recrusive function special made for this scenario, however I want to make it so abstract as possible for reuse.


Im' not quite sure that I get what you want to achieve. From sequence [1;2;3;4] you want to get [(1,2); (3,4)] or [(1,2); (2,3); (3,4)] ?

let fold f s = 
    let rec impl acc = function
        | x::y::rest -> impl ((f x y)::acc) rest
        | _ -> List.rev acc
    impl [] s    

let s = [1;2;3;4;5;6]    
let r = fold (fun x y -> x,y) s  // [(1, 2); (3, 4); (5, 6)]

let fold2 f s = Seq.pairwise s |> Seq.map f |> Seq.toList
let r2 = fold2 id s // [(1, 2); (2, 3); (3, 4); (4, 5); (5, 6)]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜