[Haskell-beginners] function nesting again
daniel.is.fischer at web.de
Thu Jan 28 08:49:43 EST 2010
Am Donnerstag 28 Januar 2010 12:40:16 schrieb Magnus Therning:
> On Thu, Jan 28, 2010 at 11:18, Zbigniew Stanasiuk <zbigergofun at gmail.com>
> > Hallo all,
> > I have two functions f and g of one arguments:
> > f :: (Num a) => [a] -> [a]
> > g :: (Num a) => [a] -> [a]
> > I can do composition (f .f .f.) [a] or (g .g .g.) [a] for a few
> > repeated functions.
> > And what about if I want to nest f, say, many many times?
> > The matter is more complicated (from my prespective :-) ) if I would
> > like to get e.g.:
> > the composition (g .f .g. g.f .f) [a]
> > if t == 0 then f else g
> > and having the list [1,0,1,1,0,0] as a pattern to construct above
> > composition.
> > How to make above, generally for arbitrary length ???
> I believe what you want is a fold over a list of functions, where this
> list has been created by mapping the if-statement above of a list of
> Bools (I know you used 0,1 above, but True,False is a better choice in
> my opinion). So, in other words, something like this:
> composeFnG l = foldl (.) id $ map chooseForG l
> chooseForG b = if b then f else g
> or a bit shorter
> composeFnG = foldl (.) id . map (\ b -> if b then f else g)
Better use foldr, at least if f and (or) g are lazy.
More information about the Beginners