Erlang if语句并返回true

Tha*_*ela 1 erlang erlang-shell

我想知道,erlang的if语句和返回值背后的想法(在这种情况下是true-> true).这是我的代码片段

if
 (Velocity > 40) -> io:format(" processing fast !~n") ;
 true -> true
end,
Run Code Online (Sandbox Code Playgroud)

我知道Erlang不允许你有一个if if without true statement选项.但即使我可以使用true-> false但它对最终输出无关紧要.

实际上if子句和返回值背后的想法是什么.

Dav*_*rth 6

Erlang的if是布尔表达式的简单模式匹配并返回结果.

它真的只需要匹配的东西,你根本不需要"真实 - >真实"的情况

例如:

if
 (Velocity > 40) -> io:format(" processing fast !~n") ;
 (Velocity < 40) -> io:format(" processing slow !~n") ;
 (Velocity == 40) -> io:format(" processing eh !~n") 
end,
Run Code Online (Sandbox Code Playgroud)

没有"真实 - >"的情况,但也没有机会与其中一种模式不匹配.

原因是"if"也是一个表达式(就像erlang中的所有内容)所以,你可以这样做:

X = if 
     (Vel > 40) -> 10;
     (Vel < 40) -> 5
    end,
Run Code Online (Sandbox Code Playgroud)

如果Vel == 40,X的值是多少?它将是未定义的,因此erlang要求您始终匹配.

当您不想指定详尽匹配时,常见的事情是使用true,如:

X = if 
     (Vel > 40) -> 10;
     (Vel < 40) -> 5;
     true -> 0
    end,
Run Code Online (Sandbox Code Playgroud)

在最后一种情况下,X总是有一个值(10,5或0)

合理?