我正在通過NLPWP Book的方式工作,我在處理遞歸函數的章節中。用於計算的雙字母組遞歸函數如下:學習haskell:創建skip-bigrams的遞歸函數
bigram :: [a] -> [[a]]
bigram [] = []
bigram [_] = []
bigram xs = take 2 xs : bigram (tail xs)
如果我在wordlist = ["colorless", "green", "ideas", "sleep", "furiously"]
運行它,我得到這個:
bigram chomsky
[("colorless","green"),("green","ideas"),("ideas","sleep"),("sleep","furiously")]
演習說:
A skip-bigram is any pair of words in sentence order. Write a function skipBigrams that extracts skip-bigrams from a sentence as a list of binary tuples, using explicit recursion. Running your function on
["Colorless", "green", "ideas", "sleep", "furiously"]
should give the following output:
Prelude> skipBigrams ["Colorless", "green", "ideas", "sleep", "furiously"]
[("Colorless","green"),("Colorless","ideas"),("Colorless","sleep"),("Colorless","furiously"),("green","ideas"),("green","sleep"),("green","furiously"),("ideas","sleep"),("ideas","furiously"),("sleep","furiously")]
這裏是定義我試過了:
skipBigram [] = []
skipBigram [_] = []
skipBigram (x:xs) = [(x, (head xs)), (x, skipBigram xs)]
但我發現了以下錯誤:
Occurs check: cannot construct the infinite type: t ~ [(t, t)]
Relevant bindings include
xs :: [t] (bound at :3:15)
x :: t (bound at :3:13)
skipBigram :: [t] -> [(t, t)] (bound at :1:1)
In the expression: interactive:IHaskell384.skipBigram xs
In the expression: (x, interactive:IHaskell384.skipBigram xs)
其中,新哈斯克爾,因爲我,我沒有絲毫瞭解。什麼是無限類型?相關的綁定?
我應該如何界定skipBigram
解決這個編譯時錯誤?
太棒了。你能解釋它是如何工作的嗎? – Jono
@Jono查看引用列表解析 –
您可以省略單例情況 - x:xs情況正確覆蓋它。 –