switch语句可以有多个变量的更多? [英] Can the switch statement have more than one variable?

查看:799
本文介绍了switch语句可以有多个变量的更多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是基于在所有使用该开关组的语言(C ++,C#PHP,Java,Python和等)。 ?那么,有可能有这样的事情。



 开关(VAR1,VAR2)
情况下VAR1 = A:
的东西
中断;
情况下VAR2 = B:
的东西
中断;
情况下VAR1 = 0,VAR2 = 1
等...


解决方案

是/否。



没有一个开关的声明传统的语言有这个。它确实存在于一些所谓的模式匹配。



C#,Java的,PHP和Python不支持模式匹配(不能完全肯定PHP,但我不'不敢相信它。纠正我,如果我错了)。



下面是在Haskell一个例子,模式匹配确实存在。模式匹配是很多实用的风格语言。

 函数1 _ =第一个参数有一个
功能_ 1 =第二个参数是一个
功能_ _ =我不知道你在什么过去了疯狂号

当该功能被调用,运行时/编译/谁检查它会看到,如果第一函数可以被调用。如果可以,它将返回值。然后,它会不断,直到它可以找到一些比赛,对于给定参数的作品。该_是说:什么都可以在这里,我真的不在乎它是如此不将值绑定到一个什么名字只是一种方式。如果我关心的价值,我可以这样做:

 函数1 =第二个参数是++(显示) 

现在,因为它通常会自上而下(不像switch语句),这是更类似于一个如果不是刚刚跳转到正确的位置switch语句/人。这只是一个非常好看的if / else。此外,如果我重新排序它,因此最常见的情况是在该文件的顶部,其他情况下会被忽略。



您也可以做与模板类似的东西,但只会在编译时工作。


The question is based in all the languages that use the switch block (C++, C# PHP , Java , Python and so on). So is it possible to have something like this?

switch (var1, var2)
case  var1 = a:
    something
    break;
case var2 = b:
    something
    break;
case var1 = 0 ,var2 = 1
     etc...

解决方案

Yes/No.

No traditional language with a "switch" statement has this. It does exist in something called "pattern matching".

C#, Java, PHP, and Python do not support pattern matching (not completely sure about PHP, but I don't believe it does. Correct me if I'm wrong).

Here's an example in Haskell where pattern matching does exist. Pattern matching is in a lot of functional style languages.

function 1 _ = "first parameter has a one"
function _ 1 = "second parameter is a one"
function _ _ = "I don't know what crazy number you passed in"

When that function is called, the runtime/compiler/whoever checks it will see if the first function can be called. If it can, it returns that value. It then keeps going until it can find some match that works for the given parameters. The "_" is just a way of saying, "anything can be here, and I really don't care what it is so don't bind the value to a name". If I cared about the value, I could do:

function 1 a = "second parameter is " ++ (show a)

Now since it usually goes top-down (unlike the switch statement), this is more akin to an if/else than a switch statement which just jumps to the correct spot. It's just a very nice looking if/else. Also, if I reordered it so the most general case was at the top of the file, the other cases would be ignored.

You can also do something similar with templates, but that will only work at compile time.

这篇关于switch语句可以有多个变量的更多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆