【发布时间】:2016-05-06 06:46:10
【问题描述】:
我编写了一个函数,它将比较两个列表并检查第一个是否是第二个的前缀,并且必须使用递归来完成。
例如:
prefix [1,2] [1,2,3]
>True
prefix [2,1,4] [2,1,13,4]
>False
现在我已经这样做了,但我觉得效率低下:
prefix :: [Int] -> [Int] -> Bool
prefix (x:xs) (y:ys)
| null xs = True
| x == y && head xs == head ys = True && prefix xs ys
| head xs /= head ys = False
我希望它可以更有效地完成,并通过一些更好的模式匹配。可以吗?
【问题讨论】:
-
捕捉缺失模式的一个好方法是使用
-fwarn-incomplete-patterns或只使用-Wall运行GHC。通常,将{-# OPTIONS_GHC -Wall #-}写在文件顶部。
标签: list haskell recursion boolean pattern-matching