[Haskell-beginners] Regular expressions in case

Daniel Fischer daniel.is.fischer at web.de
Fri Feb 12 17:04:12 EST 2010


Am Freitag 12 Februar 2010 22:05:57 schrieb legajid:
> Hi,
> is it possible to write regular expressions in case .. of ?
>
> I tried it, with no success.
>
> a x =
>     case x of
>         "a1"     -> "A1"
>         "a2"     -> "A2"
>         "a*"     -> "A*"
>         "b1"     -> "B1"
>         _     -> "_"
>
>
> for x="a3", result is _, instead of A* that i wanted.
>
> Thks,
> Didier

No, case expressions use "pattern  matching" as in 
http://haskell.org/onlinereport/exps.html#sect3.17
, that is, matching on constructors, not "pattern matching" as in matching 
a regex pattern. You can do a little like that with wildcard patterns,

a x =
    case x of
      "a1" -> "A1"
      "a2" -> "A2"
      ('a':_) -> "A*"
      "b1" -> "B1"
      _ -> "_"

in a simple case like the above. In more complicated situations, use a mix 
of pattern matching and guards,

import Text.Regex.PCRE

a' x =
    case x of
      "a1" -> "A1"
      ('a':rest)
        | rest =~ "[0-9]*" -> optAGen
        | cond1 rest -> opt1
        | cond2 rest -> opt2
      "b1" -> "B1"
      blah
        | blah =~ "[0-9]*" -> optNum
      _ -> defaultOption



More information about the Beginners mailing list