【问题标题】:Haskell: selecting lists from a list when a condition is trueHaskell:当条件为真时从列表中选择列表
【发布时间】:2012-01-10 00:55:01
【问题描述】:

当条件为真时,我正在尝试从列表中选择一些列表,如下所示:

我已经做了一个数据结构 -> data File = File {name :: String, size :: Integer, comment :: String} deriving Show

我已经创建了一个库,其中包含以下结构的所有文件:

文件 = [["name1",size1,"comment1"],["name2",size2,"coment2"],["name3",size3,"comment3"],...]

现在我需要的是一个函数,它可以选择所有大小为例如 >= 500 的列表,例如

list = select ((>=500.size) files)

如果我有:

files = [["asd",345,"coment1"],["fgh",678,"coment2"],["hjk",123,"coment3"],...]

我会得到:

list = [["fgh",678,"coment2"]]

任何帮助将不胜感激。

提前致谢。

【问题讨论】:

    标签: list haskell select


    【解决方案1】:

    前奏包含有用的

    filter :: (a -> Bool) -> [a] -> [a]
    

    你想让你的select做什么。

    回答您对 Jon Purdy 的回答的评论:

    filter ((>= 500) . size) files
    

    旁白:

    files = [["asd",345,"coment1"],["fgh",678,"coment2"],["hjk",123,"coment3"],...]
    

    不起作用,列表是同质的。它应该在问题的上下文中是

    files = [File "asd" 345 "coment1", File "fgh" 678 "coment2", ... ]
    

    File 已使用记录语法定义,您可以将其与记录语法或普通位置语法一起使用,无论在给定情况下哪个更好。记录语法会比上面的更多类型,但如果你使用它,files = [File{ name = "asd", size = 345, comment = "coment1" }, ... ] 将继续工作,如果你向类型添加字段 - 然后添加的字段将用 undefined 实例化,这可能会更好,也可能不会更好比没有更改就无法编译的代码。

    【讨论】:

    • 谢谢丹尼尔,我的错误是当数据结构中的实际名称是 filesize 时我调用了 size 并且我以为我在做一些一种错误。谢谢队友
    【解决方案2】:

    你想要filter :: (a -> Bool) -> [a] -> [a],它在前奏曲中。

    A quick Hoogle query 将帮助您在未来找到类似的东西。

    【讨论】:

    • 我确实在尝试使用过滤器,我的疑问是,我如何命令只过滤大小?
    • @seph: filter ((>=500) . size) list 应该没问题。中缀运算符 (>=) 的部分应用称为 section,并且必须放在括号中。您可以按照通常的方式使用size 编写它。
    • 是的,伙计,我也犯了这个错误,忘记括号了,现在一切都清楚了,谢谢。
    【解决方案3】:

    使用类似的输入文件

    data File = File {name :: String, size :: Integer, comment :: String}
              deriving Show
    
    files = [File "asd" 345 "coment1",
             File "fgh" 678 "coment2",
             File "hjk" 123 "coment3"]
    

    那么你可以使用

    filter :: (a -> Bool) -> [a] -> [a]
    

    这样得到你想要的:

    filter ((>= 500) . size) files
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      • 2014-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多