功能组合是使用一个功能的输出作为另一个功能的输入的过程.如果我们学习作文背后的数学会更好.在数学中,组成由 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()函数的输入并返回输出:"这是偶数".