views:

47

answers:

1

Hello,

I already searched the Web, I have Real World Haskell but I can't figure how to print a list of lists of Integers when that list is returned by combinatoricsGeneration.combinations.

I found the module at http://www.polyomino.f2s.com/david/haskell/combinatorics.html The functions have no type signature, so Haskell has to infer everything. I even tried adding signatures but the error is still there (more specific one).

The source code I am using from that module is:

combinationsOf 0 _ = [[]]
combinationsOf _ [] = []
combinationsOf k (x:xs) = map (x:) (combinationsOf (k-1) xs)
                          ++ combinationsOf k xs

combinations k n = combinationsOf k [1..n]

I added the following signatures to see if that made a difference but it did not:

combinationsOf :: Integer -> [a] -> [[a]]
combinations :: Integer -> Integer -> [[Integer]]

My Haskell source file is:

module Main
    where
        import IO
        import qualified CombinatoricsGeneration as CG

        main = putStr $ unlines $ map show CG.combinations(6, 8)

The compilation of CombinatoricsGeneration is ok. But the one of my source file produces an error:

$ ghc --version
The Glorious Glasgow Haskell Compilation System, version 6.12.3
$ ghc -c CombinatoricsGeneration.hs 
$ ghc -o test  CombinatoricsGeneration.o test.hs 

test.hs:6:37:
Couldn't match expected type `[a]'
       against inferred type `t -> t1 -> [[t1]]'
In the second argument of `map', namely `CG.combinations'
In the second argument of `($)', namely
    `map show CG.combinations (6, 8)'
In the second argument of `($)', namely
    `unlines $ map show CG.combinations (6, 8)'

However the following line works fine:

main = putStr $ unlines $ map show [[1,2],[2],[3]]

Could you help me to display that simple list ?

TIA

+3  A: 

You are calling the function wrongly. (6, 8) is a tuple (Num a1, Num a2) => (a1, a2), so

CG.combinations(6, 8)

will actually require a signature of CG.combinations as

(Num a1, Num a2) => (a1, a2) -> b

instead of a1 -> a2 -> b.

There is also a problem in precedence because map show will apply on the function CG.combinations, instead of the result of CG.combinations (6, 8).

You should call the function as

putStr $ unlines $ map show (CG.combinations 6 8)
-- #                        ^^^^^^^^^^^^^^^^^^^^^
KennyTM
It works perfectly. Thanks.
Ludovic Kuty