Haskell - 用防护罩替换外壳

标签 haskell

我想知道这部分代码是否可以用守卫替换 case 语句:

firstFunction  :: String -> Maybe MyType
secondFunction :: MyType -> Integer
myFunction     :: String -> Maybe Integer
myFunction xs = case firstFunction xs of
    Nothing -> Nothing
    Just x  -> Just( secondFunction x )

提前谢谢您!

最佳答案

您可以使用 pattern guard [Haskell-wiki] ,例如:

myFunction :: String -> Maybe Integer
myFunction xs | Just x <- firstFunction xs = Just (secondFunction x)
              | otherwise = Nothing

但是你在这里所做的基本上是“fmapfirstFunction的结果,例如:

myFunction :: String -> Maybe Integer
myFunction xs = <b>fmap secondFunction</b> (firstFunction xs)

fmap::Functor f => (a -> b) -> f a -> f b 用于“映射”仿函数。现在也许是一个仿函数,defined as :

instance Functor Maybe  where
    fmap _ Nothing = Nothing
    fmap f (Just a) = Just (f a)

这基本上就是您在此处编写的逻辑。

关于Haskell - 用防护罩替换外壳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53351881/

相关文章:

haskell - 如何使 Maybe 的这个替代定义起作用?

haskell - 导入时如何隐藏运算符?

haskell - 我可以将字符串切成头尾后用作整个字符串吗(:as) and using recursion on it in Haskell?

data-structures - 在 Haskell 代数数据类型中的备选方案中进行选择

haskell - 约束镜片

haskell - 带约束的循环类型

haskell - 所有 Haskell 仿函数都是内仿函数吗?

haskell - Haskell 的 $-Operator 的定义

Haskell 守卫未被满足

haskell - 仿函数实例声明中的箭头运算符?