[Haskell-cafe] Help with generalizing function

Luke Palmer lrpalmer at gmail.com
Mon Jun 23 04:11:46 EDT 2008


On Mon, Jun 23, 2008 at 6:30 AM, leledumbo <leledumbo_cool at yahoo.co.id> wrote:
> I've successfully create a function to return lists of N-ple that satisfy the
> following function:
> x1 + x2 + x3 + ... + xN = C
> But unfortunately, it's not generic. The N is supposed to be an input, too.
> I don't know how to make a dynamic N-ple (is it possible anyway?).
> Currently, here's the implementation:
> [code]
> findAllAns c = [ (x1,x2,x3,x4,x5) |
>    x1 <- [0..c],
>    x2 <- [0..c],
>    x3 <- [0..c],
>    x4 <- [0..c],
>    x5 <- [0..c],
>    x1 + x2 + x3 + x4 + x5 == c
>  ]
> [/code]

You will not be able to do this with a straight list comprehension
without using recursion.  It may help you to know that:

    [ e | x <- as, y <- bs ]   -- for any expression e

Is equivalent to

    concat [ [ e | y <- bs ] | x <- as ]

That is a way commas in list comprehensions can be factored out.

Luke


More information about the Haskell-Cafe mailing list