【问题标题】:f# generating a next value functionf# 生成下一个值函数
【发布时间】:2020-02-23 05:52:17
【问题描述】:

给定一个列表 [1, 2] 我正在尝试创建一个匿名函数来生成一个 (下一个值 * 生成下一个值的函数) ...类似于

f = createFunc([1; 2])
(v1, f1)  = f()    //v1 = Some 1
(v2, f2)  = f1()   //v2 = Some 2
(v3, f3)  = f2()   //v3 = None

我可以在 Elixir 中轻松做到这一点,但在 F# 中我的头撞到了墙上。任何指点都感激不尽。到目前为止,我的尝试看起来像:

let top_and_tail (l: list<'a>): (Option<'a> * list<'a>) = 
    match l with
        | [] -> (None, [])
        | h :: t -> ((Some h), t)


let rec createFun l = 
    fun() -> 
        let (h, t) = top_and_tail(l)
        (h, createFun(t))

【问题讨论】:

  • 这个实现有什么问题?
  • 我的 fsi (fsharpi) 给了我一个错误类型不匹配。期望 ''a' 但给定了 'unit -> Option * 'a' 类型 ''a' 和 'unit -> Option * 'a' 不能统一。
  • 你试过注释createFun的类型吗?

标签: recursion f# generator


【解决方案1】:

尝试将类型注释添加到函数的签名中。它的返回类型取决于l 的长度。您可以通过定义递归类型来解决它:

data Ret a = 
| End of a
| KeepGoing of a * (unit -> Ret a)

【讨论】:

  • 是的,这有效(即使没有 End 构造函数)。非常感谢你和 glennsl
  • 由于某种原因无法格式化 - ``` type ISLA = |更多的 (unit -> Option * ISLA) let top_and_tail (l: list): (Option * list) = match l with | []->(无,[])| h :: t -> ((Some h), t) let rec cf(l:list) : (unit -> (Option * ISLA)) = fun() -> let (h, t ) = top_and_tail(l) let f = cf(t) (h, More f) //(h, More cf(t)) 不起作用 let f = cf([1; 2; 3]) let (v1,更多 f1) = f() 让 (v2, 更多 f2) = f1() 让 (v3, 更多 f3) = f2() 让 (v4, 更多 f4) = f3() ```
猜你喜欢
  • 1970-01-01
  • 2016-05-12
  • 1970-01-01
  • 1970-01-01
  • 2011-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-19
相关资源
最近更新 更多