当我有两个功能时:
一种)
three :: Int -> Maybe Int
three a
| a == 3 = Just 3
| otherwise = Nothing
b)
takeOne :: Int -> Int
takeOne a = (a - 1)
我如何调用函数 a 作为函数 b 的参数?即我如何让函数 b 接受一个 'Maybe Int' 代替一个 'Int'?
在我尝试的那一刻
takeOne (three 3)
我收到错误:
ERROR - Type error in application
*** Expression : takeThree (three 3)
*** Term : three 3
*** Type : Maybe Int
*** Does not match : Int
谢谢。
最佳答案
您有几个选择,但我认为最简单的是 fmap
:
fmap :: Functor f => (a -> b) -> f a -> f b
例子:
> fmap takeOne $ three 3
Just 2
> fmap takeOne $ three 2
Nothing
另一种选择是使用函数
maybe
,它采用默认值,一个应用于 Just
内的任何值的函数,然后是 Maybe a
将此应用于。一个例子应该清楚> maybe 0 takeOne $ three 3
2
> maybe 0 takeOne $ three 2
0
如果您只想提供默认值,另一种选择是使用函数
fromMaybe
来自 Data.Maybe
:> import Data.Maybe
> fromMaybe 0 $ three 3
3
> fromMaybe 0 $ three 2
0
在 Haskell 中,有一个名为
Functor
的类型类。定义为class Functor f where
fmap :: (a -> b) -> f a -> f b
有很多很多类型是
Functor
的实例。 .事实上,所有参数化的数据结构都是Functor
s,所有 Applicative
s 和 Monad
s。最简单的心智模型 Functor
是它只是一个容器的花哨名称。对于列表,fmap = map
, 例如。它所做的只是在容器内的元素上映射一个函数。更多的例子是:
> fmap (+1) (Left "error")
Left "error"
> fmap (+1) (Right 1)
Right 2
> x <- fmap (++", world") getLine
Hello
> x
Hello, world
> fmap (+1) [1..5]
[2,3,4,5,6]
> fmap (+1) ("fst", 2)
("fst", 3)
偶函数是
Functor
!这里fmap = (.)
,这只是正常的函数组合:> let lengthPlusOne = fmap (+1) length
> lengthPlusOne "Hello"
6
关于Haskell - 如何使用返回 'Maybe Int' 作为另一个函数的参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26387251/