[英]Haskell: List append operation
我正在研究Haskell解決的99個問題 。 我試圖在這里了解一些基礎知識。
combinations :: Int -> [a] -> [[a]]
combinations _ [] = [[]]
combinations 0 _ = [[]]
combinations k (x:xs) = x_start ++ others
where x_start = [ x : rest | rest <- combinations (k-1) xs ]
others = if k <= length xs then combinations k xs else []
考慮, combinations 1 [3, 4]
模式與combinations k (x:xs)
匹配。 我們將從計算x_start開始,它將是x_start = [3 : combinations 0 [4]]
combinations 0 [4]
將與combinations 0 [4]
和“返回” [[]]
模式匹配(1個elem空列表的列表)
我們現在看到x_start = [3 : combinations 0 [4]] ===> x_start = [3 : [[]]]
。 這個對嗎? 如果是這樣,那么x_start會是什么,按列表前綴運算符:
操作, x_start = [[3, []]]
與[[3]]不同嗎?
當我嘗試用ghci打印時,它抱怨
No instance for (Num [t0]) arising from a use of ‘it’
In a stmt of an interactive GHCi command: print it
我們將從計算x_start開始,它將是x_start = [3:組合0 [4]]
這是不正確的,因為x_start
和others
類型都是[[a1]]
類型。 因此,更有可能x_start = [3] : rest
,那里要rest
了(因為列表理解只是combinations 0 [4]
列表Monad <-
用法的語法糖)。 由於定義combinations 0 [4]
是[[]]
,因此只有一個值- []
。 最后, [3] : []
是[[3]]
。
正如評論中提到的那樣,ghci無法很好地鍵入[3 : [[]]]
表達式,因為第一個元素是Num a,第二個元素是列表列表,而不是Num
列表。 這就是編譯器要說的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.