【问题标题】:What is the difference between Cond and Case?康德和凯斯有什么区别?
【发布时间】:2018-09-19 21:43:01
【问题描述】:

在 Elixir 编程语言中, 有两个相似的构造 condcase。 两者都类似于来自其他语言的 switchselect 语句

condcase 都在 this page 上进行了描述

【问题讨论】:

    标签: switch-statement elixir


    【解决方案1】:

    让我也将if 加入俱乐部。您将if 与一个条件和一个可能的else 一起使用,就是这样。当您有多个条件并且if 语句不够时,您使用cond 语句,最后,当您想要模式匹配某些数据时使用case 语句。

    我们举例说明:假设今天下雨想吃苹果,下雨想吃米饭,那么你可以这样使用:

    if weather == :raining do
      IO.puts "I'm eating apple"
    else
      IO.puts "I'm eating rice"
    end
    

    这是一个有限的世界,所以你想扩大你的选择,因此你会在某些情况下吃不同的东西,所以cond 声明就是为此,像这样:

    cond do
      weather == :raining and not is_weekend ->
        IO.puts "I'm eating apple"
      weather == :raining and is_weekend ->
        IO.puts "I'm will eat 2 apples!"
      weather == :sunny ->
        IO.puts "I'm happy!"
      weather != :raining and is_sunday ->
        IO.puts "I'm eating rice"
      true ->
        IO.puts "I don't know what I'll eat"
    end
    

    最后一个true 应该在那里,否则会引发异常。

    那么case 呢?它用于模式匹配某些东西。假设您收到有关天气和星期几的信息作为元组中的消息,并且您依靠它来做出决定,您可以将您的意图写成:

    case { weather, weekday } do
      { :raining, :weekend } ->
        IO.puts "I'm will eat 2 apples!"
    
      { :raining, _ } ->
        IO.puts "I'm eating apple"
    
      { :sunny, _ } ->
        IO.puts "I'm happy!"
    
      { _, :sunday } ->
        IO.puts "I'm eating rice"
    
      { _, _ } ->
        IO.puts "I don't know what I'll eat"
    end
    

    所以case 为您带来了数据的模式匹配方法,这是ifcond 所没有的。

    【讨论】:

      【解决方案2】:

      我的简单回答是:

      • cond 不接收任何参数,它允许您在每个分支中使用不同的条件。
      • case 接收一个参数,每个分支都与参数模式匹配

      【讨论】:

        猜你喜欢
        • 2023-03-18
        • 2017-07-16
        • 2019-07-03
        • 1970-01-01
        • 1970-01-01
        • 2017-06-08
        • 2021-10-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多