2016-08-04 5 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 

パターン(_:[])は、リスト内の1つの要素の最小値を持っていることを前提としています。あなたのコードでは、最初のリストが空で、2番目のリストが空でない場合があります。

+0

それとも、それは 'longer [] _ = False'であることを意図していましたか? – zigazou

+1

私はOPのためにそれを残しています。 :) – Sibi

2

4つのケースが必要ですが、2つのシングルトンリストを別々のケースとして扱う必要はありません。

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 

は実際に、あなただけのことになっているものlonger [] _に応じて、適切な順序で3例が必要です。

-- 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. 
関連する問題