【问题标题】:Haskell List Recursion mistake?Haskell列表递归错误?
【发布时间】:2013-05-08 07:05:46
【问题描述】:

嘿,我是 Haskell 的新手。

所以我想消除列表中所有大于 500 的整数。

import Data.List

leng x = if(head x > 500) then leng(tail x) else [head x]++leng(tail x)

我得到了正确的输出,但在每个输出的末尾是

例外:Prelude.head:空列表

如何解决这个问题?

【问题讨论】:

  • 一般来说,你应该使用(h:t)而不是[h]++t(所以这里是(head x):(leng (tail x)))。 (:) 是 Haskell 的 cons 函数,将单个项目添加到列表的前面。

标签: list haskell recursion


【解决方案1】:
-- You need this to stop the recursion, otherwise it would try to split the list 
-- when   there are no elements left.
    leng [] = []

您可以将此视为您的方法的停止条件。

你也可以重写你的方法如下:

leng [] =[]
leng (x:xs) | x > 500 = leng xs
            | otherwise = x : leng xs

在使用 haskell 中的列表时,第一个语句经常重复出现。例如

last [x]    = x
-- the underscore means the value of the variable is not needed and can be ignored.
last (_:xs) = last xs

【讨论】:

    【解决方案2】:

    添加:

    leng [] = []
    

    在当前leng x之前。

    但你也可以这样做:

    leng x = filter (<=500) x
    

    甚至

    leng = filter (<=500)
    

    【讨论】:

      猜你喜欢
      • 2019-07-21
      • 1970-01-01
      • 2013-01-17
      • 2011-07-16
      • 2015-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多