我可以在Erlang做自己的卫兵吗? [英] Can I make my own Guards in Erlang?

查看:108
本文介绍了我可以在Erlang做自己的卫兵吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  is_char(Ch) - > 
如果Ch < 0 - >假;
Ch> 255 - >假;
true - >真
结束。

is_string(Str) - >
case is_list(Str)of
false - >假;
true - >列表:all(is_char,str)
end。

它是Guard Alwais梦寐以求的,因为它检查输入是否是一个字符串 - 怎么过,我不允许在erlang使用它,为什么会这样?有没有工作?



我想要写出如下内容:

  Fun(Str)when is_string(Str) - > STR; 
fun(Int)when is_integer(Int) - > io:format(〜w,[Int])。

或者更好地在邮件上使用。

解决方案

您不能在防护装置中使用用户定义的功能。这是因为警卫中的功能必须没有副作用(例如在你的函数中使用 io:format )。在守卫中,您仅限于以下内容:




  • 用于类型测试的BIF( is_atom is_constant is_float is_integer is_list is_number is_pid is_port is_reference is_tuple is_binary is_function is_record ),

  • 布尔运算符( andalso orelse ; ),

  • 关系运算符(> > = =< =:= == = / = / = ) ,

  • 算术运算符( + - * div rem ),

  • 按位运算符( band bor bxor bnot bsl bsr ),

  • 其他没有副作用的BIF( abs / 1 元素/ 2 hd / 1 length / 1 node / 1,2 round / 1 size / 1 tl / 1 trunc / 1 self / 0


I came accross this code on the web:

is_char(Ch) ->         
    if Ch < 0 -> false;  
       Ch > 255 -> false;
       true -> true      
    end.

is_string(Str) ->            
    case is_list(Str) of           
    false -> false;           
    true -> lists:all(is_char, Str)
    end.

Its is the Guard I alwais dreamed off, in that it checks if an input is a string -- how ever, I'm not allowed to use it in erlang, why is this? And is there a work around?

I would like to be able to write stuff like:

Fun(Str) when is_string(Str) -> Str;
Fun(Int) when is_integer(Int) -> io:format("~w", [Int]).

or even better use it on messages.

解决方案

You are not allowed to use user defined functions in the guards. It is because the functions in the guards have to be free from side effects (such as using io:format in your functions). In guards, you are limited to the following:

  • BIFs used for type tests (is_atom, is_constant, is_float, is_integer, is_list, is_number, is_pid, is_port, is_reference, is_tuple, is_binary, is_function, is_record),
  • boolean operators (not, and, or, andalso, orelse, ,, ;),
  • relational operators (>, >=, <, =<, =:=, ==, =/=, /=),
  • arithmetic operators (+, -, *, div, rem),
  • bitwise operators (band, bor, bxor, bnot, bsl, bsr),
  • other BIFs that are free of side effects (abs/1, element/2, hd/1, length/1, node/1,2, round/1, size/1, tl/1, trunc/1, self/0)

这篇关于我可以在Erlang做自己的卫兵吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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