如何通过文字进行模式匹配并同时为其分配变量?

Jas*_*hio 1 variables binding haskell pattern-matching variable-assignment

我如何将这两者结合起来,以便能够进行模式匹配,同时在变量中具有匹配的文字?

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
Run Code Online (Sandbox Code Playgroud)

Li-*_*Xia 12

首先 bind a,然后对其进行模式匹配,因此它在所有分支的范围内。

fun a = case a of
  1 -> ...
  55 -> ...
  123 -> ...
  _ -> ...
Run Code Online (Sandbox Code Playgroud)

或者使用 as-patterns。

fun a@1 = ...
fun a@55 = ...
fun a@123 = ...
fun a = ...
Run Code Online (Sandbox Code Playgroud)

另见例如https://www.haskell.org/tutorial/patterns.html