erlang - Erlang 中的一等模式? (备择方案)

标签 erlang pattern-matching elixir first-class

有没有办法在 Erlang 中创建一等的模式?我需要能够创建模式并将其作为参数传递给其他函数,但我知道模式在 Erlang 中并不是一等的。我也研究过 Elixir,但就模式而言,它似乎没有提供更多东西。

我想知道是否有人想出了一个简单的解决方案来解决这个问题。我正在考虑尝试实现这样的事情:

% Instead of using variables, we would just use uppercase atoms which would serve as vars
% A passable pattern
Pattern = {ok, 'Result'}. 

% Custom function to check for matches
match(pattern, {ok, [1,2,3]}). % => true

我是 Erlang 新手,所以也许这是完全没有必要的。也许有一个库可以做这种事情?

非常感谢任何建议。提前致谢!

最佳答案

我不知道是否已经存在可以实现您想要的功能的东西,但您可以像这样轻松实现它:

-module (match).

-compile([export_all]).

-define(MF(S), fun(S) -> true; (_)->false end).


match(F,V) -> F(V).


test() ->
    Pattern = ?MF({ok,_}),
    false = match(Pattern,{error,reason}),
    true = match(Pattern,{ok,[1,2,3]}).

关于erlang - Erlang 中的一等模式? (备择方案),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22949127/

相关文章:

javascript - 解析单个用户输入字符串以获取高级搜索条件

C/C++ 与 Erlang 共享内存

Erlang:如何从 Mnesia 集群中删除节点

erlang - 作为钢筋依赖的雅司病

html - 如何在 eex 中将自定义 HTML 添加到功能链接 (Phoenix.HTML.link)

elixir - (ArgumentError) 参数错误 - 尝试将值列表传递到变更集时

Erlang float_to_binary 奇怪地截断小数

https - 带有http和https的Webmachine?

F# 过于激进的类型推断?

java - 如何使用Java中的模式来获取像C中的 'sscanf'那样的组?