[Haskell-beginners] function nesting again
Magnus Therning
magnus at therning.org
Thu Jan 28 06:40:16 EST 2010
On Thu, Jan 28, 2010 at 11:18, Zbigniew Stanasiuk <zbigergofun at gmail.com> wrote:
> 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
where
chooseForG b = if b then f else g
or a bit shorter
composeFnG = foldl (.) id . map (\ b -> if b then f else g)
/M
--
Magnus Therning (OpenPGP: 0xAB4DFBA4)
magnus@therning.org Jabber: magnus@therning.org
http://therning.org/magnus identi.ca|twitter: magthe
More information about the Beginners
mailing list