Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Pattern Matching on Strings - Why doesn't this work?

getMultiWordPortion :: String -> String
getMultiWordPortion (x:':':xs) = xs
getMultiWordPortion _ = ""

The expected result from pattern matching in this code is that everything before the first colon get's assigned to x, and everything afterwards gets assigned to xs, which is the result. If there is no colon, nothing is returned.

What actually happens with a sample string I'm using ("PING :gibson.freenode.net" - it's part of an IRC client) is that I get the blank return value.

What am I doing wrong here?

like image 229
Macha Avatar asked Sep 05 '10 12:09

Macha


2 Answers

The pattern x:':':xs means "The first character is x, the second character is ':' the remaining characters are in the list xs". So this means that the type of x is Char, not [Char] and that the pattern only matches if there's exactly one character before the colon.

There is no way to use pattern matching on lists to say "match one sublist, followed by an element, followed by the remaining list".

To get the substring after the first colon you can use dropWhile (/= ':') theString. This will include the colon, so use tail or pattern matching to remove it.

like image 179
sepp2k Avatar answered Oct 19 '22 00:10

sepp2k


The : operator conses one element to the head of a list. Your pattern will only match a string where the colon is the second item in the list.

like image 38
Greg Sexton Avatar answered Oct 19 '22 00:10

Greg Sexton