简体   繁体   中英

Haskell filtered string to list

I want a fuction where you put in a String like "Hello I am 25 years old!" and get a list out of it like ["hello","i","am","years","old"]. 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. 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).

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.

  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] . Search for exactly this type signature via hoogle and you will find the function words second in the result list.

  2. a method which does uppercase would mostly like have the type signature Char -> Char . Type this into hoogle and you will find toUpper in third in the list.

  3. is a letter: Char -> Bool

  4. next open ghci and try out the functions. IE:

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

    <interactive>:1:1: Not in scope: 'isUpper' -- you need to import Data.Char

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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