如何在Haskell中返回元组列表

Ste*_*ion 0 haskell list

我正在使用C++中的优化类,并且一直在尝试重新编写Haskell中的实验室以获得踢腿和咯咯笑声.这一过程非常艰难但非常有趣.

我正在尝试编写一个返回3个整数元组列表的函数,如下所示:

[(1,1,1),(1,2,1),(1,3,2)]

这是我一直试图使用的代码:

sortToTuples :: (Num a) => [a] -> Int -> Int -> [(Int,Int,a)]
sortToTuples [] _ _ = []
-- i and j are passed as 1 and 1.
sortToTuples (x:xs) i j   
    | j > 9         = [(i+1, 1, x)] ++ sortToTuples (xs i+1 1)
    | otherwise     = [(i, j+1, x)] ++ sortToTuples (xs i, j+1)
Run Code Online (Sandbox Code Playgroud)

该函数用于获取表示数独谜题的平面列表并返回元组列表(i,j,x),其中i是行值,j是列值,x是单元格的值.

无论出于何种原因,haskell对我的类型签名非常不满意:

Prelude> :l quicksort.hs 
[1 of 1] Compiling Main             ( quicksort.hs, interpreted )

quicksort.hs:23:44:
    Couldn't match expected type `[(Int, Int, a)]'
                with actual type `Int -> Int -> [(Int, Int, a0)]'
    In the return type of a call of `sortToTuples'
    Probable cause: `sortToTuples' is applied to too few arguments
    In the second argument of `(++)', namely
      `sortToTuples (xs i + 1 1)'
    In the expression: [(i + 1, 1, x)] ++ sortToTuples (xs i + 1 1)
Failed, modules loaded: none.
Prelude> 
Run Code Online (Sandbox Code Playgroud)

bhe*_*ilr 6

这里有一点语法错误

| j > 9 = [(i+1, 1, x)] ++ sortToTuples (xs i+1 1)
| otherwise = [(i, j+1, x)] ++ sortToTuples (xs i, j+1)
Run Code Online (Sandbox Code Playgroud)

你应该是几乎正确的

... sortToTuples xs (i+1) 1
... sortToTuples xs i (j+1)
Run Code Online (Sandbox Code Playgroud)

这样每个参数都单独传递给sortToTuples.

为了解释编译器错误,它将其(xs i+1 1)视为单个参数,并且因为它解析是正确的Haskell,它认为第一个参数sortToTuples应该具有类型[a],因此它认为sortToTuples (xs i+1 1)应该具有类型Int -> Int -> [(Int, Int, a)].