问题
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