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

标签 variables haskell binding 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

最佳答案

首先绑定(bind)a,然后对其进行模式匹配,使其在所有分支的范围内。

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

或者使用 as-patterns。

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

参见示例 https://www.haskell.org/tutorial/patterns.html

关于variables - 如何通过文字进行模式匹配并同时为其分配变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60526257/

相关文章:

haskell - GHC优化: Collatz conjecture

c# - Wpf 实时数据绑定(bind)到 ListView

wpf - 文本框中的绑定(bind)不起作用

ios - 无法将 VC 变量与方法中检索到的变量相关联

swift - 通过文本域调用变量名

java - 当文本和变量同时使用 System.out.println 时出现错误

haskell - 列表理解中的守卫不会终止无限列表?

optimization - GHC 可以可靠地执行哪些优化?

c# - 如何在 ListBox 中包含按钮并映射它们的事件?

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP