练习多重组合,列表中的函数
Exercise Multicomposition , functions in list
这是一个练习:
-- Ex 12: recall the binary function composition operation
-- (f . g) x = f (g x). In this exercise, your task is to define a function
-- that takes any number of functions given as a list and composes them in the
-- same order than they appear in the list.
--
-- Examples:
-- multiCompose [] "foo" ==> "foo"
-- multiCompose [] 1 ==> 1
-- multiCompose [(++"bar")] "foo" ==> "foobar"
-- multiCompose [reverse, tail, (++"bar")] "foo" ==> "raboo"
-- multiCompose [(3*), (2^), (+1)] 0 ==> 6
-- multiCompose [(+1), (2^), (3*)] 0 ==> 2
作为初学者,我无法解决这个问题。
我试了很多方法,这个不行:
multiCompose [] = (1*) $
multiCompose fs = (multiCompose (init fs)) (last fs) $
根据我目前的理解,它应该可以工作,因为它可以开发如下:
multicompose [(+1), (2^), (3*)] = multiCompose [(+1), (2^)] (3*) $
= multiCompose [(+1)] (2^) $ (3*) $
= multiCompose [] (+1) $ (2^) $ (3*) $
= (1*) $ (+1) $ (2^) $ (3*) $
我的问题
- 你能帮我给出这个练习的有效答案吗?
- 你能帮我理解为什么我的解决方案不起作用吗?
非常感谢
你忘记了参数,还有一个$
:
multicompose [(+1), (2^), (3*)] $ x
-- = multiCompose [(+1), (2^)] (3*) $ x
-- here |
= multiCompose [(+1), (2^)] $ (3*) $ x
= multiCompose [(+1)] $ (2^) $ (3*) $ x
= multiCompose [] $ (+1) $ (2^) $ (3*) $ x
= (+1) $ (2^) $ (3*) $ x
而不是 [a,b,c,d] = [a,b,c] ++ [d]
,使用身份 [a,b,c,d] = [a] ++ [b,c,d] = a : [b,c,d]
:
= (+1) $ (2^) $ (3*) $ x
= (+1) $ (2^) $ (3*) $ multiCompose [ ] $ x
= (+1) $ (2^) $ multiCompose [ (3*)] $ x
= (+1) $ multiCompose [ (2^), (3*)] $ x
你可以从这里拿走。特别是,multiCompose [] x = x
必须成立,并且是 []
参数案例的有效定义。
这是一个练习:
-- Ex 12: recall the binary function composition operation
-- (f . g) x = f (g x). In this exercise, your task is to define a function
-- that takes any number of functions given as a list and composes them in the
-- same order than they appear in the list.
--
-- Examples:
-- multiCompose [] "foo" ==> "foo"
-- multiCompose [] 1 ==> 1
-- multiCompose [(++"bar")] "foo" ==> "foobar"
-- multiCompose [reverse, tail, (++"bar")] "foo" ==> "raboo"
-- multiCompose [(3*), (2^), (+1)] 0 ==> 6
-- multiCompose [(+1), (2^), (3*)] 0 ==> 2
作为初学者,我无法解决这个问题。 我试了很多方法,这个不行:
multiCompose [] = (1*) $
multiCompose fs = (multiCompose (init fs)) (last fs) $
根据我目前的理解,它应该可以工作,因为它可以开发如下:
multicompose [(+1), (2^), (3*)] = multiCompose [(+1), (2^)] (3*) $
= multiCompose [(+1)] (2^) $ (3*) $
= multiCompose [] (+1) $ (2^) $ (3*) $
= (1*) $ (+1) $ (2^) $ (3*) $
我的问题
- 你能帮我给出这个练习的有效答案吗?
- 你能帮我理解为什么我的解决方案不起作用吗?
非常感谢
你忘记了参数,还有一个$
:
multicompose [(+1), (2^), (3*)] $ x
-- = multiCompose [(+1), (2^)] (3*) $ x
-- here |
= multiCompose [(+1), (2^)] $ (3*) $ x
= multiCompose [(+1)] $ (2^) $ (3*) $ x
= multiCompose [] $ (+1) $ (2^) $ (3*) $ x
= (+1) $ (2^) $ (3*) $ x
而不是 [a,b,c,d] = [a,b,c] ++ [d]
,使用身份 [a,b,c,d] = [a] ++ [b,c,d] = a : [b,c,d]
:
= (+1) $ (2^) $ (3*) $ x
= (+1) $ (2^) $ (3*) $ multiCompose [ ] $ x
= (+1) $ (2^) $ multiCompose [ (3*)] $ x
= (+1) $ multiCompose [ (2^), (3*)] $ x
你可以从这里拿走。特别是,multiCompose [] x = x
必须成立,并且是 []
参数案例的有效定义。