Romas Augustinavičius
Romas Augustinavičius

Reputation: 443

Haskell list construction

Can somebody please explain what this function does in "otherwise" guard?

getWord :: String -> String
getWord [] = []
getWord (x:xs)
  | elem x spaces = []
  | otherwise = x: getWord xs

I don't realy get it what happens to x?

Upvotes: 0

Views: 149

Answers (2)

Mikkel
Mikkel

Reputation: 782

otherwise is just True (see Prelude).

getWord pattern-matches on a string, which is a list of characters, and if x is not a space character then it will keep adding (consing) characters until it reaches a space or the end of the string i.e. it will return the first word in a sentence.

Upvotes: 1

AJF
AJF

Reputation: 11913

: is the list constructor:

(:) :: a -> [a] -> [a]

Eg:

λ> 1 : [1,2,3]
[1,1,2,3]
λ> 'h' : "ello"
"hello"

In that expression, x : getWord xs simply creates a list starting with x, and ending with getWord xs, which causes the recursion here.

Upvotes: 6

Related Questions