函数组合是将一个函数的输出用作另一个函数的输入的过程。在数学中,合成用f{g(x)}表示,其中g()是一个函数,其输出用作另一个函数(即f())的输入。
如果一个函数的输出类型与第二个函数的输入类型匹配,则可以使用这两个函数来实现函数组合。我们使用点运算符(.)在Haskell中实现函数组合。
看下面的示例代码。演示如何使用函数组合来计算输入数字是偶数还是奇数。
eveno :: Int -> Bool
noto :: Bool -> String
eveno x = if x `rem` 2 == 0
then True
else False
noto x = if x == True
then "This is an even Number"
else "This is an ODD number"
main = do
putStrLn "Example of Haskell Function composition"
print ((noto.eveno)(16))
在这里,在main函数中,同时调用了两个函数noto和eveno。编译器将首先以16作为参数eveno()函数并此调用。此后,编译器将使用eveno函数的输出作为noto()函数的输入。
执行上面示例代码输出结果如下-
Example of Haskell Function composition
"This is an even Number"
由于提供数字16作为输入(它是偶数),因此eveno()函数返回true,导致noto()函数的输入并返回输出:"This is an even Number"。
上一篇:
Haskell其他函数
下一篇:
Haskell模块
