【问题标题】:Haskell filtered string to listHaskell过滤字符串到列表
【发布时间】:2014-11-12 06:27:55
【问题描述】:

我想要一个函数,你可以在其中输入一个字符串,比如“你好,我 25 岁!”并从中得到一个列表,例如 ["hello","i","am","years","old"]。所以它应该把所有大写字母都放在小写字母中,并删除所有不是字母的东西。它应该只使用 Data.List 和 Data.Char。 我知道我应该在字符串上使用单词然后过滤它,但我就是想不通(是的,我是 Haskell 的新手)。

toString :: String -> [String]
toString str = ...

【问题讨论】:

  • 类似filter (not . null) . map (filter Data.Char.isLower . map Data.Char.toLower) . words。可以将其视为从右到左书写的三个阶段:在每个单词内打破空格,转换为低位并删除多余的单词,然后最终消除空单词。

标签: string list haskell filter


【解决方案1】:

冒着回答家庭作业问题的风险:

import Data.Char

toString :: String -> [String]
toString str = filter (not . null) . map (map toLower . filter isAlpha) . words $ str

Prelude Data.Char> toString "Hello I am 25 years old!"
["hello", "i", "am", "years", "old"]

【讨论】:

  • 之前有过这个但我收到了这个错误所以我打开了这个问题Couldt match expected type [String]' with actual type String -> [[Char]]' 在表达式中:filter (not . null) 。 map (map toLower . filter isAlpha) . words 在 `getWords' 的等式中: getWords str = filter (not . null) 。 map (map toLower . filter isAlpha) .单词
  • 如果您在函数定义中定义了str 参数,那么您还需要将其传递给函数实现。它应该是getWords str = ... str 或getWords = ...
【解决方案2】:

这将是我的工作流程:使用 hoogle 并使用您需要的类型签名。

  1. 关于如何获取单词列表:您需要一个函数 foo 执行“一二三”-> [“一”、“二”、“三”],因此它具有类型签名:String -> [String]。通过hoogle搜索该类型签名,你会在结果列表中找到函数words第二个。

  2. 一个大写的方法最喜欢有类型签名Char -> Char。在hoogle中输入这个,你会在列表的第三个找到toUpper。

  3. 是一个字母:Char -> Bool

  4. 接下来打开 ghci 并尝试这些功能。即:

    ghci> :t toUpper -- will print the type of isUpper

    <interactive>:1:1: Not in scope: ‘isUpper’ -- 你需要导入Data.Char

    ghci> import Data.Char -- 所以让我们导入 Data.Char

    ghci> toUpper "abc"

    ghci> words "a quick brown fox"

    ghci> :t map

    ghci> map toUpper ["a", "quick"]

...等等

您仍然需要弄清楚如何将这些部分与地图和过滤器组合在一起,但我再次建议您仔细查看类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 2010-09-22
    • 2022-01-16
    • 2014-11-27
    • 2017-05-10
    相关资源
    最近更新 更多