[英]How to return a list of tuples in Haskell
我正在使用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)
該函數用於獲取表示數獨難題的平面列表,並返回元組(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>
您這里有點語法錯誤
| j > 9 = [(i+1, 1, x)] ++ sortToTuples (xs i+1 1)
| otherwise = [(i, j+1, x)] ++ sortToTuples (xs i, j+1)
您幾乎正確了,應該是
... sortToTuples xs (i+1) 1
... sortToTuples xs i (j+1)
這樣,每個參數將分別傳遞給sortToTuples
。
為了解釋編譯器錯誤,它將(xs i+1 1)
視為單個參數,並且由於它解析正確的Haskell,因此認為sortToTuples
的第一個參數應為[a]
類型,因此它認為sortToTuples (xs i+1 1)
應該具有Int -> Int -> [(Int, Int, a)]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.