gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:04:57 25 4
gpt4 key购买 nike

有没有办法在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com