Home > Blockchain >  Exercise Multicomposition , functions in list
Exercise Multicomposition , functions in list

Time:11-28

This is an exercise:

-- 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

As beginner, I am not able to solve that. I tried many approach, this one does not work :

multiCompose [] = (1*) $
multiCompose fs = (multiCompose (init fs)) (last fs) $

Following my current understanding, it should work since it can be developed as follow :

multicompose [( 1), (2^), (3*)] = multiCompose [( 1), (2^)]           (3*) $ 
                                = multiCompose [( 1)]         (2^) $  (3*) $ 
                                = multiCompose []     ( 1) $  (2^) $  (3*) $ 
                                =              (1*) $ ( 1) $  (2^) $  (3*) $

My questions

  1. Could you help me with a valid answer to this exercise ?
  2. Could you help me to understand why my solution does not work ?

Thank you so much

CodePudding user response:

Your forgot the argument, and one more $:

     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

Instead of [a,b,c,d] = [a,b,c] [d], use the identity [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

You can take it from here. In particular, multiCompose [] x = x must hold, and is a valid definition for the [] argument case.

  • Related