Dodande
Dodande

Reputation: 99

How to get string from a text til first space with a recursive function?

In my homework, my task is to write a recursive function which returns the first word of a text and "" if the first character is a space.

Here is my function:

takeWord :: [Char] -> [Char]
takeWord [] = []
takeword (x:xs) 
    | x == ' ' = []
    | otherwise = x : takeword xs

It should work like this:

takeWord " one"    = ""
takeWord "one two" = "one"
takeWord ""        = ""    --returns with "Non-exhaustive patterns in function takeword"
takeWord "one"     = "one" --and this too

But at the cases where is no space, it returns with this error message:

Non-exhaustive patterns in function takeword

What would be the correct code?

Upvotes: 3

Views: 90

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476547

You defined two functions here: takeWord, with an uppercase W, and takeword with a lowercase w. The former one only works with empty lists, the latter one only works with non-empty lists.

You thus should pick one of the two names, like:

takeWord :: [Char] -> [Char]
takeWord [] = []
takeWord (x:xs) 
    | x == ' ' = []
    | otherwise = x : takeWord xs

we can make it a bit more elegant by matching with a space in the pattern, and not in the guard:

takeWord :: [Char] -> [Char]
takeWord [] = []
takeWord (' ':_) = ""
takeWord (x:xs) = x : takeWord xs

Note that you can make use of takeWhile :: (a -> Bool) -> [a] -> [a] here:

takeWord :: [Char] -> [Char]
takeWord = takeWhile (' ' /=)

Upvotes: 6

Related Questions