练习多重组合,函数在列表中



这是一个练习:

-- 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*) $

我的问题

  1. 你能帮我给出这个练习的有效答案吗
  2. 你能帮我理解为什么我的解决方案不起作用吗

非常感谢

您忘记了参数,还有一个$:

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必须保持,并且是[]参数情况的有效定义。

最新更新