2016-08-04 108 views
0

非窮盡的方式,我得到非詳盡模式例外下面的代碼哈斯克爾:在功能

--determine which list is longer 
longer::[a]->[a]->Bool 
longer [] [] = False 
longer _ [] = True 
longer (_:[]) (_:[]) = False 
longer (_:xs) (_:ys) = longer xs ys 

我不明白我在做什麼錯在這裏。

+3

使用:'ghc -Wall prog.hs'和ghc應該告訴你沒有考慮到的模式。 – ErikR

回答

4

您還沒有處理這種情況下:

longer [] _ = undefined 

模式(_:[])假設您已經在列表中最小的一個元素。在你的代碼中,當第一個列表是空的,第二個列表不可以是空的。

+0

或者它可能意味着'更長[] _ =假'? – zigazou

+1

我要離開那個OP。 :) – Sibi

2

您需要4個案例,但您不需要將兩個單例列表視爲單獨的案例。

longer :: [a] -> [a] -> Bool 

-- 1) Two empty lists 
longer [] [] = False 
-- 2) An non-empty list and an empty list 
longer _ [] = True 
-- 3) An empty list and a non-empty list 
longer [] _ = ??? 
-- 4) Two non-empty lists 
longer (_:xs) (_:ys) = longer xs ys 

其實,你只需要按照正確的順序3例,這取決於longer [] _應該是。

-- First case: if longer [] _ is suppose to be True 
longer :: [a] -> [a] -> Bool 
longer [] [] = True 
longer (_:xs) (_:ys) = longer xs ys 
-- We get this far if one is empty and the other is not, 
-- but we don't care which one is which. 
longer _ _ = False 

-- Second case: if longer [] _ is supposed to be False 
longer :: [a] -> [a] -> Bool 
longer (_:xs) (_:ys) = longer xs ys 
longer _ [] = True 
longer [] _ = False -- This covers longer [] [] as well.