代码之家  ›  专栏  ›  技术社区  ›  Ludovic Kuty

打印由Com返回Haskell的整数列表二进制生成.组合

  •  1
  • Ludovic Kuty  · 技术社区  · 15 年前

    我在 http://www.polyomino.f2s.com/david/haskell/combinatorics.html

    我在该模块中使用的源代码是:

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

    我添加了以下签名,看看这是否会产生影响,但事实并非如此:

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

    我的Haskell源文件是:

    module Main
        where
            import IO
            import qualified CombinatoricsGeneration as CG
    
            main = putStr $ unlines $ map show CG.combinations(6, 8)
    

    $ 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)'
    

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

    TIA公司

    1 回复  |  直到 15 年前
        1
  •  3
  •   kennytm    15 年前

    (6, 8) 是元组 (Num a1, Num a2) => (a1, a2)

    CG.combinations(6, 8)
    

    实际上需要签名 CG.combinations 作为

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

    a1 -> a2 -> b

    在优先级上也有一个问题,因为 map show 将应用于函数 CG.组合 CG.combinations (6, 8) .

    您应该将函数调用为

    putStr $ unlines $ map show (CG.combinations 6 8)
    -- #                        ^^^^^^^^^^^^^^^^^^^^^