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 )
先感谢您!
解决方案
您可以使用模式保护[Haskell-wiki],例如:
myFunction :: String -> Maybe Integer
myFunction xs | Just x <- firstFunction xs = Just (secondFunction x)
| otherwise = Nothing
但是您在这里所做的基本上是“ fmap
”的结果firstFunction
,例如:
myFunction :: String -> Maybe Integer
myFunction xs = fmap secondFunction (firstFunction xs)
fmap :: Functor f => (a -> b) -> f a -> f b
用于在仿函数上“映射”。NowMaybe
是一个仿函数,定义为:
instance Functor Maybe where fmap _ Nothing = Nothing fmap f (Just a) = Just (f a)
这基本上就是你在这里写的逻辑。
推荐阅读
- ffmpeg - 检测视频帧偏移以智能方式同步视频
- angular - Angular 服务类单元测试失败,无法解析所有参数
- svn - svn - 使本地分支与远程分支相同
- android - 非常简单的 android 应用程序崩溃,因为 View 为空
- c# - 向表 C# 动态添加新行
- snakemake - snakemake 在 conda 环境中找不到可执行文件
- regex - 正则表达式匹配一个字符串并否定另一个
- php - 如何使用教义/symfony4 从数据库中获取(连接)两条记录
- java - 如何删除 int 数组中指定元素的第一次出现?(爪哇)
- reactjs - 使用 ESLint 规则反应 Redux