非窮盡的方式,我得到非詳盡模式例外下面的代碼哈斯克爾:在功能
--determine which list is longer
longer::[a]->[a]->Bool
longer [] [] = False
longer _ [] = True
longer (_:[]) (_:[]) = False
longer (_:xs) (_:ys) = longer xs ys
我不明白我在做什麼錯在這裏。
非窮盡的方式,我得到非詳盡模式例外下面的代碼哈斯克爾:在功能
--determine which list is longer
longer::[a]->[a]->Bool
longer [] [] = False
longer _ [] = True
longer (_:[]) (_:[]) = False
longer (_:xs) (_:ys) = longer xs ys
我不明白我在做什麼錯在這裏。
您需要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.
使用:'ghc -Wall prog.hs'和ghc應該告訴你沒有考慮到的模式。 – ErikR