这是我到目前为止所拥有的:
type Maybe<'a> = option<'a>
let succeed x = Some(x)
let fail = None
let bind rest p =
match p with
| None -> fail
| Some r -> rest r
let rec whileLoop cond body =
if cond() then
match body() with
| Some() ->
whileLoop cond body
| None ->
fail
else
succeed()
let forLoop (xs : 'T seq) f =
using (xs.GetEnumerator()) (fun it ->
whileLoop
(fun () -> it.MoveNext())
(fun () -> it.Current |> f)
)
whileLoop
可以很好地支持for
循环,但我看不到如何支持 while 循环。部分问题是 while 循环的翻译使用delay
,在这种情况下我无法弄清楚。下面明显的实现可能是错误的,因为它不会延迟计算,而是运行它!
let delay f = f()
没有延迟也有try...with
障碍try...finally
。