【发布时间】:2016-03-31 17:41:33
【问题描述】:
我有两个功能:
f :: a -> Maybe a
g :: a -> a
我想创建这样的功能:
h :: a -> Maybe a
h x
| isJust(f x) = Just (g $ fromJust(f x))
| otherwise = Nothing
我怎样才能以更优雅的方式做到这一点?
【问题讨论】:
-
优雅的方式贴在下面。不过,我想提醒一下,使用
isJust/fromJust可以说是最不优雅的方式。事实上,如果忘记了isJust检查,fromJust可能会使您的程序崩溃。更好的方法是使用模式匹配,例如case f x of Nothing -> Nothing ; Just y -> Just $ g y。另请参阅boolean blindness 了解更多信息。 -
类型不正确。
g (fromJust (f x)) : a。我想你提醒Just (g (fromJust (f x))。
标签: function haskell functional-programming dot-operator