too*_*mas 3 haskell functional-programming maybe
我已经做了一些研究,但找不到任何东西。我不明白这样的功能是如何工作的:
func :: Maybe (Int) -> Maybe (Int)
Run Code Online (Sandbox Code Playgroud)
我应该如何进行模式匹配?我已经尝试过了,但是没有用:
func Just a = Just a | otherwise = Nothing
func Nothing = Just Nothing | otherwise = Nothing
Run Code Online (Sandbox Code Playgroud)
我该如何进行这项工作?
错误信息:
Run Code Online (Sandbox Code Playgroud)exercises6.hs:83:22: error: parse error on input ‘|’ | 83 | func Just a = Just a | otherwise = Nothing | ^
您可以在两种可能的情况下进行模式匹配。A Maybe a具有两个数据构造函数:a Nothing和a Just …,…其包装的值。| otherwise模式匹配时没有任何内容。竖线字符(|)用于警卫 [lyah]。
因此,您可以例如使用以下方法增加a中的值Just:
func :: Maybe Int -> Maybe Int
func (Just x) = Just (x+1)
func Nothing = NothingRun Code Online (Sandbox Code Playgroud)
Just x如@chepner所说,此处需要使用方括号。否则,它将被解析为好像Just是第一个参数,并且x是第二个参数。
由于Maybe是Functortypeclass的实例,因此可以在fmap :: Functor f => (a -> b) -> f a -> f b这里使用:
func :: Maybe Int -> Maybe Int
func = fmap (1+)Run Code Online (Sandbox Code Playgroud)