How can I define this lazy (infinite?) data structure in F#

本秂侑毒 提交于 2020-01-03 18:18:15

问题


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."

I am getting

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)'

回答1:


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."

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



来源:https://stackoverflow.com/questions/20338032/how-can-i-define-this-lazy-infinite-data-structure-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!