[英]Haskell function composition
I've defined a function f1 and f2,so that I can use at the and the function composition ( fkomp
), which is supposed to use f1 and f2 to calculate 2^x
by every element in a given List. 我定义了一个函数f1和f2,以便可以在和函数组合( fkomp
)上使用它,应该使用f1和f2来计算给定List中的每个元素2^x
。
f1 :: Int -> Int
f1 x = product (replicate x 2)
f2 :: (a -> b) -> [a] -> [b]
f2 f xs = [f x | x <- xs]
fkomp :: [Int] -> [Int]
fkomp xs = f2 f1 $ xs
It works,but the problem is,that i can't write my code with composition: 它可以工作,但是问题是我无法编写具有组成部分的代码:
fkomp xs = f2.f1 $ xs
I've been typing every single combination but it doesn't work with composition. 我一直在输入每种组合,但不适用于合成。
Could someone lighten my path ? 有人可以照亮我的路吗?
Thanks a lot 非常感谢
Ok, let's look just at the types (it's like a puzzle - the types have to fit): 好的,让我们看一下类型(就像一个谜题-类型必须适合):
f1 :: Int -> Int
f2 :: (a -> b) -> [a] -> [b] = (a -> b) -> ([a] -> [b])
in order to compose the both you need ones co-domain to be the same as the others domain. 为了组成两者,您需要一个共同域与另一个共同域。
This is because the composition has type: 这是因为合成具有类型:
(.) :: (b -> c) -> (a -> b) -> a -> c
See the b
has to fit ;) 看到b
必须适合;)
So for your f1
and f2
you would need either Int ~ (a -> b)
or Int ~ ([a] -> [b])
both of which are not working well (as you found out). 因此,对于您的f1
和f2
您将需要Int ~ (a -> b)
或Int ~ ([a] -> [b])
两者均无法正常工作(如您所知)。
BUT you kind of have the ability to apply f1
to f2
as f1
just fits f2
first argument (as you have seen too) - so I am a bit confused why you even want to use composition here. 但是您有能力将 f1
应用于f2
因为f1
恰好适合f2
第一个参数(您也已经看到)-所以我有点困惑为什么您甚至想在这里使用合成。
your functions are a bit strange - I think the usual way to write them would be 您的函数有点奇怪-我认为编写它们的通常方法是
f1 x = 2 ^ x
f2 = map
or even 甚至
fkomp :: [Int] -> [Int]
fkomp = map (2^)
note that the last one is not function-composition but (just as your case) function-application: I apply the function (2^) :: Int -> Int
to map :: (Int -> Int) -> [Int] -> [Int]
and get a function of type [Int] -> [Int]
as the result (if you check the types in GHCi you will see a more generic versions but I think this is a bit more clear) 请注意,最后一个不是函数组成,而是(视情况而定)函数应用:我将函数(2^) :: Int -> Int
应用于map :: (Int -> Int) -> [Int] -> [Int]
并得到类型为[Int] -> [Int]
的函数(如果您检查GHCi中的类型,您将看到一个更通用的版本,但我认为这更加清楚了)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.