简体   繁体   English

F#为列表编写自定义折返函数

[英]F# Writing custom foldback function for list

I am learning F#. 我正在学习F#。 I have written custom fold function for list (with help here on StackOverflow). 我已经为列表编写了自定义折叠功能(在StackOverflow的帮助下)。 I am now trying to write foldback function say myOwnFoldBack. 我现在正在尝试编写折返函数,例如myOwnFoldBack。 The expected output might be myOwnFoldBack (+) 0 [1; 2; 3 ] 预期的输出可能是myOwnFoldBack (+) 0 [1; 2; 3 ] myOwnFoldBack (+) 0 [1; 2; 3 ] myOwnFoldBack (+) 0 [1; 2; 3 ] should return 6 . myOwnFoldBack (+) 0 [1; 2; 3 ]应返回6

Here is my code for myOwnFold 这是我的myOwnFold代码

let rec myOwnFoldf s0 =
  function
  | [] -> s0
  | x::tail -> myOwnFoldf (f s0 x) tail

This works fine. 这很好。 Here is code for myOwnFoldBack 这是myOwnFoldBack的代码

let rec myOwnFoldBack  f s0 =
  function
  | [] -> 0
  | x::tail -> x f (myOwnFoldBackf tail)

The error I get is: 我得到的错误是:

Type mismatch. Expecting a
    'a    
but given a
    ('b -> 'a -> int) list -> int    
The resulting type would be infinite when unifying ''a' and '('b -> 'a -> int) list -> int'

I think I figured it out finally! 我想我终于明白了!

let rec myOwnFoldBack  f s0 =
  function
  | [] -> s0
  | x::tail ->    f  x (myOwnFoldBack f s0 tail)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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