[英]Haskell filtered string to list
我想要一个函数,在其中输入“你好,我25岁!”之类的字符串。 并从中获取列表,例如[“ hello”,“ i”,“ am”,“年”,“旧”]。 因此,应将所有大写字母都小写,并删除所有不包含字母的内容。 它应该只使用Data.List和Data.Char。 我知道我应该在字符串上使用单词,然后对其进行过滤,但是我无法弄清楚(是Haskell的新手)。
toString :: String -> [String]
toString str = ...
冒着回答作业问题的风险:
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"]
关于如何获取单词列表:您需要一个函数foo
,该函数执行“ one two two”-> [“ one”,“ two”,“ three”],因此它具有类型签名: String -> [String]
。 通过hoogle精确搜索此类型签名,您将在结果列表中第二找到功能words
。
一个大写的方法通常希望具有类型签名Char -> Char
。 将其键入到hoogle中,您将在列表的第三部分找到toUpper
。
是一个字母:Char-> Bool
接下来打开ghci并尝试功能。 IE浏览器:
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"]
... 等等
您仍然需要弄清楚如何将这些部分与地图和过滤器放在一起,但是我还是建议您仔细看一下这些类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.