# [Haskell-cafe] Style and a problem

Brent Yorgey byorgey at seas.upenn.edu
Fri Sep 10 08:57:57 EDT 2010

```On Fri, Sep 10, 2010 at 12:24:39PM +0300, Wanas wrote:
> On Fri, Sep 10, 2010 at 1:06 AM, Nils Schweinsberg <ml at n-sch.de> wrote:
>
> > Something like this?
> >
> >    import Data.List
> >
> >    newList :: Int -> [[Int]]
> >    newList n = myNub
> >        [ l | l <- undefined -- not really sure how you want
> >                             -- to generate these lists :)
> >            , sum l == sum [1..n]
> >            ]
> >
> >    myNub :: (Ord a) => [[a]] -> [[a]]
> >    myNub = nubBy (\a b -> sort a == sort b)
> >
> >
> > - Nils
> >
> So I've checked out this code, and it doesn't compile on ghci. My version,
> without the "undefined" portion is(which still doesn't work):
>
> import Data.List
>
> newList :: Int -> [[Int]]
> newList n = myNub [ l | l <- [1..n], sum l == sum [1..n] ]

The reason this doesn't compile is that

l <- [1..n]

means l will take on each of the values 1 through n in turn.  So l is
of type Int.  But then you do 'sum l' which requires l to be a list.
So clearly that does not typecheck.  But I'm not quite sure I
understand what you actually want l to be.  Do you want it to run
through all lists of a certain length with elements chosen from
[1..n]?  In that case you could do something like

import Control.Monad  -- for replicateM

...

[ l | l <- replicateM n [1..n], ... ]

which will generate all length-n lists with elements chosen from
[1..n].  If you wanted all lists with lengths from 1 to n and elements
chosen from 1 to n, you could do

[ l | len <- [1..n], l <- replicateM len [1..n], ... ]

As others have pointed out there are likely far more efficient ways to
do what you want, but I'm just trying to help you get this code to
work first, even if it's inefficient.

-Brent

```