如何解决为什么这个流类型的展平函数会给我这个错误?
exception Empty_list
type 'a stream = Stream of 'a * (unit -> 'a stream) | Nil
let shead s = match s with
| Stream (a,_) -> a
| Nil -> raise Empty_list
let stail s = match s with
| Stream (_,s) -> s ()
| Nil -> raise Empty_list
let sflatten ( s : 'a stream ) =
let rec sflatten_sub (s : 'b stream) parent =
match s with
| Nil -> parent ()
| Stream (child,tl) ->
match child with
| _ -> Stream ( shead s,fun () -> sflatten_sub (tl ()) parent )
| Stream (_,_) ->
sflatten_sub (shead s) (fun () -> sflatten_sub (tl ()) parent)
in sflatten_sub s (fun () -> Nil)
当我将它输入到 ocaml 解释器时(当然最后有一个 ;;
),我收到这个错误,我不明白出了什么问题。
Line 21,characters 23-32:
21 | sflatten_sub (shead s) (fun () -> sflatten_sub (tl ()) parent)
^^^^^^^^^
Error: This expression has type 'a stream
but an expression was expected of type 'a stream stream
The type variable 'a stream occurs inside 'a stream stream
解决方法
这是您对 mmm
的前两次递归调用:
sflatten_sub
这两个调用中的第一个参数将具有相同的类型。由于 sflatten_sub (tl ()) parent
sflatten_sub (shead s) (fun () -> ... )
返回 tl ()
,我得出结论 'a stream
也返回 shead s
。既然'a stream
的头部是一个流,那么s
一定是一个流的流。
换句话说,在我看来,s
没有为 shead s
的第一个参数返回正确类型的值。它返回一个流元素(类型 sflatten_sub
),但 'a
的第一个参数应该是一个流(类型 sflatten_sub
)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。