2016-11-26 14 views
2

下面我顯示輸出。如果他們不相等,我給出了一個數字列表,然後返回False並正確工作。但是,如果數字列表相等,那麼它不會返回True。你能檢查這個代碼嗎?每個數字的列表不等於假的工作,但在相同的數字它不工作

la [] = True 
la a = 
     if ((head a)==head (tail a)) 
      then la (tail a) 
      else False 

輸出:

Cw2016> la [1,2,2] 
False 
Cw2016> la [2,2,2] 

Program error: pattern match failure: head [] 

Cw2016> la [2,2,3] 
False 
Cw2016> la [0,1,3] 
False 
Cw2016> la [0,0,3] 
False 
Cw2016> la [0,0,0] 

Program error: pattern match failure: head [] 

Cw2016> 
+1

逐步評估'la [1]'。 –

+1

'la(x:xs)'自從'head(x:xs)= x'和'tail(x:xs)= xs'後更容易閱讀 – wizzup

回答

6

的問題是,在第二個分支,你只知道列表具有尺寸至少爲1,但你正在尋找的第二個參數。我建議你使用模式匹配替換頭和尾(這部分功能):

la [] = True 
la (x0:x1:xs) = 
     if (x0 == x1) 
      then la (x1:xs) 
      else False 

如果調用GHC與-W,你會得到你的模式不包括X的警告:[] 。你可能想添加這個分支:

la (x0:[]) = True 

順帶一提,你應該簡化你的表達:

 if (x0 == x1) 
      then la (x1:xs) 
      else False 

到:

(x0 == x1) && la (x1:xs) 

爲了得到多一點技術有關的問題, a = [x]x時出現問題。首先,headtail被定義爲:

head (x:xs) = x 
head [] = undefined 

tail (x:xs) = xs 
tail [] = undefined 

然後,表達head (tail a)計算如下:

head (tail a) 
= { value of a } 
    head (tail (x:[])) 
= { first equation of tail } 
    head [] 
= { second equation of head } 
    undefined 

這就是爲什麼你會得到一個錯誤。

相關問題