How to do pattern matching via a literal and assign a variable to it at the same time?

Viewed 87

How do I combine these two, to be able to do pattern matching and at the same time have that matched literal in a variable?

fun1 :: Int -> String

fun1 1 = -- ..... how to bind 1 to a variable in the function declaration?
fun1 55 = -- ..... how to bind 55 to a variable in the function declaration?
fun1 123 = -- ..... how to bind 123 to a variable in the function declaration?

fun1 a = -- ...........   all is OK
1 Answers

First bind a, then pattern-match on it, so it's within scope in all branches.

fun a = case a of
  1 -> ...
  55 -> ...
  123 -> ...
  _ -> ...

Or use as-patterns.

fun a@1 = ...
fun a@55 = ...
fun a@123 = ...
fun a = ...

See also for example https://www.haskell.org/tutorial/patterns.html

Related