我喜欢计算表达式,但我会犯一些简单的错误,例如忘记 return 关键字或 !诸如 let! 之类的表达式然后返回!,或者我只是忘记写 do!。这种情况在状态单子中经常发生,我倾向于忘记状态而只关注我定义的单子运算符。
我有时会确保我的单子运算符返回“单子类型”的类型,而不是“匿名”函数。这有助于跟踪我忘记的打字,但并不是很理想。大家有更好的技巧吗?
I love computation expressions, but I make simple mistakes like forgetting the return keyword or the ! on expressions like let! and return!, or I simply forget to write the do!. This happens much with state monads where I tend to forget about the state and just focus on the monadic operators I have defined.
I sometimes make sure my monadic operators return a type that is "of monad type" instead of an "anonymous" function. This helps to track my forgetful typing, yet is not really ideal. Anybody have better tricks?
发布评论
评论(1)
给定一个典型的 monad,如果您在关键字后缺少
!
,则您的代码不应编译,因为类型无法正常工作。例如:这不会编译,因为您尝试添加两个
Async
,但如果您将let
更改为,它将编译让!
s。同样,要识别丢失的
return
,只需留意编译器警告消息和奇怪的单子类型:在这种情况下,
sum
是一个Async
code>,当您尝试在代码中的其他地方使用它时,这应该是显而易见的。或者,您可以使用类型注释来立即捕获此问题:Given a typical monad, your code shouldn't compile if you're missing a
!
after a keyword because the types won't work out. For example:This won't compile because you're attempting to add two
Async<int>
s, but it will compile if you change thelet
s tolet!
s.Similarly, to identify missing
return
s, just look out for compiler warning messages and odd monadic types:In this case,
sum
is anAsync<unit>
, which should be apparent when you try to use it elsewhere in your code. Alternatively, you can use a type annotation to catch this problem immediately: