非穷尽的方式,我得到非详尽模式例外下面的代码哈斯克尔:在功能
--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