简体   繁体   English

Haskell筛选的字符串列表

[英]Haskell filtered string to list

I want a fuction where you put in a String like "Hello I am 25 years old!" 我想要一个函数,在其中输入“你好,我25岁!”之类的字符串。 and get a list out of it like ["hello","i","am","years","old"]. 并从中获取列表,例如[“ hello”,“ i”,“ am”,“年”,“旧”]。 So it should put all uppercase letters in lowercase and delete everything that isnt a letter. 因此,应将所有大写字母都小写,并删除所有不包含字母的内容。 It should just use Data.List and Data.Char. 它应该只使用Data.List和Data.Char。 I know i should use words on the String and then filter it but i just cant figure it out (yes im new to Haskell). 我知道我应该在字符串上使用单词,然后对其进行过滤,但是我无法弄清楚(是Haskell的新手)。

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

At the risk of answering a homework question: 冒着回答作业问题的风险:

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"]

This would be my workflow: Use hoogle and work with the type signatures you need. 这就是我的工作流程:使用hoogle并使用所需的类型签名。

  1. On how to get a list of words: You need a function foo that does "one two three" -> ["one", "two", "three"] so it has the type signature: String -> [String] . 关于如何获取单词列表:您需要一个函数foo ,该函数执行“ one two two”-> [“ one”,“ two”,“ three”],因此它具有类型签名: String -> [String] Search for exactly this type signature via hoogle and you will find the function words second in the result list. 通过hoogle精确搜索此类型签名,您将在结果列表中第二找到功能words

  2. a method which does uppercase would mostly like have the type signature Char -> Char . 一个大写的方法通常希望具有类型签名Char -> Char Type this into hoogle and you will find toUpper in third in the list. 将其键入到hoogle中,您将在列表的第三部分找到toUpper

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

  4. next open ghci and try out the functions. 接下来打开ghci并尝试功能。 IE: IE浏览器:

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

    <interactive>:1:1: Not in scope: 'isUpper' -- you need to import Data.Char <interactive>:1:1: Not in scope: 'isUpper'您需要导入Data.Char

    ghci> import Data.Char -- so let´s import 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"]

... and so on ... 等等

You`ll still need to figure out how to put these parts together with map and filter but again I´d advice you to have a close look at the types. 您仍然需要弄清楚如何将这些部分与地图和过滤器放在一起,但是我还是建议您仔细看一下这些类型。

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

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