Case expressions, matching, and "constants"

Hamilton Richards hrichrds@swbell.net
Thu, 17 Jul 2003 11:09:09 -0500


At 12:03 PM +0100 7/17/03, Bayley, Alistair wrote:
>I've just debugged a program that used a case expression, but where I was
>trying to match on constants rather than literals. Here's a contrived
>example:
>
>
>>  module Main where
>>  one = 1
>>  two = 2
>>
>>  test n =
>>	case n of
>>		one -> "one"
>>		two -> "two"
>>		_ -> "three"
>>
>>  main = putStrLn (test 2)
>
>
>This initial version seems to me to be the "natural" way to write the case
>expression, but it doesn't work because the first alternative always
>succeeds.

The root of the problem is that a variable occurring in a pattern is 
always a new variable. A pattern variable provides a way to refer to 
the value to which the variable is bound when the pattern matches.

>This is what I've turned it into to get it to work. It seems a bit clumsy;
>is there a better way to write this?
>
>>  test n =
>>	case True of
>>		_ | n == one -> "one"
>>		  | n == two -> "two"
>  >		  | otherwise -> "three"

As, Graham Klyne wrote at 2:52 PM +0100 7/17/03:

>  test n | n == one  = "one"
>         | n == two  = "two"
>         | otherwise = "three"

is a neater solution.

Best,

--Ham
-- 
------------------------------------------------------------------
Hamilton Richards, PhD           Department of Computer Sciences
Senior Lecturer                  The University of Texas at Austin
512-471-9525                     1 University Station C0500
Taylor Hall 5.138                Austin, Texas 78712-1188
ham@cs.utexas.edu                hrichrds@swbell.net
------------------------------------------------------------------