簡體   English   中英

Haskell篩選的字符串列表

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

這就是我的工作流程:使用hoogle並使用所需的類型簽名。

  1. 關於如何獲取單詞列表:您需要一個函數foo ,該函數執行“ one two two”-> [“ one”,“ two”,“ three”],因此它具有類型簽名: String -> [String] 通過hoogle精確搜索此類型簽名,您將在結果列表中第二找到功能words

  2. 一個大寫的方法通常希望具有類型簽名Char -> Char 將其鍵入到hoogle中,您將在列表的第三部分找到toUpper

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

  4. 接下來打開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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM