繁体   English   中英

使Haskell List Recursion函数更有效

[英]Make Haskell List Recursion function more efficient

我编写了一个函数,该函数将比较两个列表,并检查第一个列表是否是第二个列表的前缀,并且必须使用递归来完成。

例如:

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

我希望它可以更有效地进行,并具有更好的模式匹配。 是真的吗?

您根本不需要使用head函数。 这使比较的数量增加了一倍。 尝试这个:

prefix :: [Int] -> [Int] -> Bool
prefix [] _ = True
prefix _ [] = False
prefix (x:xs) (y:ys)
  | x == y = prefix xs ys
  | otherwise = False

乍得·吉尔伯特的解决方案可以非常简化:

prefix :: [Int] -> [Int] -> Bool
prefix [] _ = True
prefix (x:xs) (y:ys)
  | x == y = prefix xs ys
prefix _ _ = False

这不会影响性能,但是会展示一种语言功能:当某个模式上的所有防护措施均失败时,该匹配将被放弃,并且匹配将在下一个模式下恢复。

 Prelude > let prefix [] _ = True
 Prelude |     prefix _ [] = False
 Prelude |     prefix (x:xs) (y:ys) = if ( x==y) then prefix xs ys else False

例子:

  Prelude> prefix [1,3] []
  False
  Prelude> prefix [] [1,2,3]
  True
  Prelude> prefix [1,2] [1,2,3]
  True

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM