以下类型取自这个问题 https://stackoverflow.com/q/50586942/633183
(* contains an error, later fixed by the OP *)
type _ task =
| Success : 'a -> 'a task
| Fail : 'a -> 'a task
| Binding : (('a task -> unit) -> unit) -> 'a task
| AndThen : ('a -> 'b task) * 'a task -> 'b task
| OnError : ('a -> 'b task) * 'a task -> 'b task
type _ stack =
| NoStack : 'a stack
| AndThenStack : ('a -> 'b task) * 'b stack -> 'a stack
| OnErrorStack : ('a -> 'b task) * 'b stack -> 'a stack
type 'a process =
{ root: 'a task
; stack: 'a stack
}
我对 OCaml 比较陌生,但我从未见过:
语法与之前一样使用。例如,我见过这样定义的多态类型,使用of
syntax
type 'a expr =
| Base of 'a
| Const of bool
| And of 'a expr list
| Or of 'a expr list
| Not of 'a expr
在最初的问题中,我不清楚这些变体是如何构造的,因为看起来每个变体都不接受参数。以这个简化的例子为例
type 'a stack =
| Foo : int stack
| Bar : string stack
;;
type 'a stack = Foo : int stack | Bar : string stack
尝试制作一个int stack
using Foo
Foo 5;;
Error: The constructor Foo expects 0 argument(s),
but is applied here to 1 argument(s)
然而,无需争论
Foo;;
- : int stack = Foo
好的,但是在哪里int
?如何存储这种类型的数据?
在下面的OP程序中,他/她“正常”匹配类型,例如Success value -> ...
or Fail value -> ...
。同样,如果变体构造函数不接受参数,如何构造该值?
let rec loop : 'a. 'a process -> unit = fun proc ->
match proc.root with
| Success value ->
let rec step = function
| NoStack -> ()
| AndThenStack (callback, rest) -> loop {proc with root = callback value; stack = rest }
| OnErrorStack (_callback, rest) -> step rest <-- ERROR HERE
in
step proc.stack
| Fail value ->
let rec step = function
| NoStack -> ()
| AndThenStack (_callback, rest) -> step rest
| OnErrorStack (callback, rest) -> loop {proc with root = callback value; stack = rest }
in
step proc.stack
| Binding callback -> callback (fun task -> loop {proc with root = task} )
| AndThen (callback, task) -> loop {root = task; stack = AndThenStack (callback, proc.stack)}
| OnError (callback, task) -> loop {root = task; stack = OnErrorStack (callback, proc.stack)}
有人可以帮助我填补我的知识空白吗?