zoukankan      html  css  js  c++  java
  • erlang 里的if 和 case

    case Expression of
    
    Pattern1 [when Guard1] -> Expr_seq1;
    
    Pattern2 [when Guard2] -> Expr_seq2;
    
    …
    
    end
    if
     Guard1 -> ...;
     Guard2 -> ...;
     ...;
    end.

     Erlang 编程指南 第三章程顺序编程里有这么一个例子

    %%test1(X) ->
    %%    if
    %%        X > 1 -> greater;
    %%        X < 1 -> smaller;
    %%        true -> equal
    %%    end.


    如果把 true 改成通配符行不行?

    %%test1(X) ->
    %%    if
    %%        X > 1 -> greater;
    %%        X < 1 -> smaller;
    %%        _ -> equal
    %%    end.

    这将得到一个unbound 错误

    如果换成case怎么实现?

    test1(X) ->
        case  X of
            X > 1 -> greater;
            X < 1 -> smaller;
            _ -> equal
        end.

    这样会爆 illegal pattern 的错误 X > 1 不是一个能被模式匹配的终值

    应该这样

    test1(1)  -> equal;
    test1(X) ->
        case  (X - 1) div abs(X - 1) of
            1 -> greater;
            -1 -> smaller
        end.


    这说明,if后面是每个 Guard(保护元表达式)  计算一值 然后匹配 true or false. 而case 是计算一次,然后从上往下匹配的, 每个pattern 只能是个确定值。

  • 相关阅读:
    JSON1
    program的发展史及两个方法
    统计字符出现的次数
    美国十大web2.0公司背后的故事
    web history-----JavaScript 的起源故事
    Baidu_Map
    My json(Demo)
    program发展史及 forecast
    js事件类型
    字符统计与正则表达式
  • 原文地址:https://www.cnblogs.com/bobolive/p/3156408.html
Copyright © 2011-2022 走看看