Haskell: gluing char and list together?

So, I have this code:

toWords :: String -> [String]
toWords "" = []
toWords (nr1 : rest)
    | nr1 == ' ' = toWords rest
    | otherwise = [nr1] : toWords rest

The towords function should simply remove all spaces and return a list with all the words. But this happens:

* Home> toWords "How are you?"

["H", "o", "w", "a", "g", "e", "y", "o", "y", "?" ]

+3
source share
4 answers

Your type must be String → [String] or [Char] → [[Char]].

Your input is a string (list of characters) that displays a list of strings (list of character characters).

Your type here means that it maps the string to ANY type, this is not true.

Edit: alternatively you can use:

splitBy :: [a] -> a -> [[a]]
splitBy [] sep = []
splitBy (nr1 : rest) if nr1 == sep then splitBy rest sep else nr1 : (splitBy rest sep)

. ( ), splitBy "string of words" ' ' [ "string", "of", "words" ].

, [] [[]], :

splitBy [] sep = [[]]
splitBy (nr1 : rest) sep = if nr1 == sep 
    then [] : splitBy rest sep 
    else (nr1 : head (splitBy rest sep)) : tail (splitBy rest sep)

: splitBy "List of things" ' ' ===> ["list","of","things"]

+4

, "" Prelude?

+5

, :

.

| nr1 == ' ' = toWords rest

, .

| otherwise = [nr1] : toWords rest

, , .

, .

, :

toWords "" = []
toWords (' ':rest) = toWords rest
toWords text       = let (word, rest) = break (== ' ') text
                     in word : toWords rest
+1

- -, ? , String, a. Haskell; String -> String String -> [Char] , .

-, , , ; , .

, , , , . , , (, Prelude), , .

0
source

Source: https://habr.com/ru/post/1746208/


All Articles