如何在F#中定义此惰性(无限)数据结构 [英] How can I define this lazy (infinite?) data structure in F#

查看:115
本文介绍了如何在F#中定义此惰性(无限)数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义一个简单的文本游标时遇到问题,该游标由一个元组表示,其中第一个元素是当前字符,如果一个函数获取下一个或崩溃,则第二个元素是当前字符.

I am having a problem defining the following simple text cursor which is represented by a tuple where the first element is a current character and the second one if a function that gets the next one or crashes.

let rec nextAt index text = 
    if index < String.length text then
        (text.[index], (fun() -> nextAt (index + 1) text))
    else
        failwith "End of string."

我得到

Error   1   Type mismatch. Expecting a
    char * (unit -> 'a)    
but given a
    'a    
The resulting type would be infinite when unifying ''a' and 'char * (unit -> 'a)'

推荐答案

您将必须使用中间类型:

You'll have to use an intermediate type:

type GetNext = GetNext of (unit -> char * GetNext)

let rec nextAt index text = 
    if index < String.length text then
        (text.[index], GetNext(fun () -> nextAt (index + 1) text))
    else
        failwith "End of string."

关于y组合器的问题的答案更深入地探讨了此限制,并提出了解决方法.

The answers to this question about y combinator explore this limitation in greater depth and pose workarounds.

这篇关于如何在F#中定义此惰性(无限)数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆