How to return a list of tuples in Haskell
I'm taking an optimization class in C++ and have been trying to recode the labs in Haskell for kicks and giggles. The going has been rough but very interesting.
I'm trying to write a function that returns a list of 3 Integer tuples like so:
[(1,1,1),(1,2,1),(1,3,2)]
Here is the code I've been attempting to use:
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)
The function is meant to take a flat list that represents a sudoku puzzle and return a list of tuples (i,j,x) where i is the row value, j is the column value, and x is the value of the cell.
For whatever reason haskell is very unhappy with my type signature:
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>
You have a bit of a syntax error here
| j > 9 = [(i+1, 1, x)] ++ sortToTuples (xs i+1 1)
| otherwise = [(i, j+1, x)] ++ sortToTuples (xs i, j+1)
You almost have it correct, it should be
... sortToTuples xs (i+1) 1
... sortToTuples xs i (j+1)
That way each argument is passed separately to sortToTuples
.
To explain the compiler error, it sees (xs i+1 1)
as a single argument, and since it parses are correct Haskell, it thinks that the first argument to sortToTuples
should have type [a]
, so it thinks that sortToTuples (xs i+1 1)
should have type Int -> Int -> [(Int, Int, a)]
.
上一篇: Functor,Applicative Functor和Monad之间的关系
下一篇: 如何返回Haskell中的元组列表