這是代碼:
listhalve :: [a] -> ([a],[a])
listhalve (x:xs)
| length [x] == length xs = ([x],xs)
| length [x] < length xs = listhalve ([x] head xs : tail xs)
| length [x] > length xs = ([x],xs)
當我運行或編譯它時沒有錯誤訊息,它只是在非對串列的情況下永遠運行。
我知道撰寫這個有效函式的不同方法。我只是想知道什么是錯,此代碼明確。
將您的意見牢記在心后,我想出了以下代碼:
listhalve :: [a] -> ([a],[a])
listhalve xs = listhalve' [] xs
where
listhalve' :: [a] -> [a] -> ([a],[a])
listhalve' x y
| length x == length y = (x, y)
| length x < length y = listhalve' (x (head y)) (tail y)
| length x > length y = (x, y)
這給了我一個錯誤閱讀:
test.hs:7:56: error:
* Occurs check: cannot construct the infinite type: a1 ~ [a1]
* In the second argument of `( )', namely `(head y)'
In the first argument of listhalve', namely `(x (head y))'
In the expression: listhalve' (x (head y)) (tail y)
* Relevant bindings include
y :: [a1] (bound at test.hs:5:22)
x :: [a1] (bound at test.hs:5:20)
listhalve' :: [a1] -> [a1] -> ([a1], [a1]) (bound at test.hs:5:9)
|
7 | | length x < length y = listhalve' (x (head y)) (tail y)
|
這段代碼有什么問題?
uj5u.com熱心網友回復:
考慮到這listhalve ([x] head xs : tail xs)與你所listhalve ([x] xs)使用的相同listhalve (x:xs),因此會導致無窮無盡的遞回。
uj5u.com熱心網友回復:
當您指定head y為串列時,即[head y]. 完整的、更正的函式如下所示:
listhalve :: [a] -> ([a],[a])
listhalve xs = listhalve' [] xs
where
listhalve' :: [a] -> [a] -> ([a],[a])
listhalve' x y
| length x == length y = (x, y)
| length x < length y = listhalve' (x [head y]) (tail y)
| length x > length y = (x, y)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/394430.html
上一篇:結構歸納haskell
