目录

Haskell - 功能组合( Function Composition)

Function Composition是使用一个函数的输出作为另一个函数的输入的过程。 如果我们学习composition背后的数学会更好。 在数学中, compositionf{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函数中,我们同时调用两个函数evenoeveno 。 编译器将首先使用16作为参数调用函数"eveno()" 。 此后,编译器将使用eveno方法的输出作为eveno noto()方法的输入。

其产出如下 -

Example of Haskell Function composition                
"This is an even Number"

由于我们提供数字16作为输入(这是偶数), eveno()函数返回true ,它成为eveno()函数的输入并返回输出:“这是偶数”。

↑回到顶部↑
WIKI教程 @2018