模式匹配在Erlang [英] pattern match in Erlang

查看:149
本文介绍了模式匹配在Erlang的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习一些Erlang,而我遇到这些Erlang模式匹配问题。
给定模块:

I am trying to learn some Erlang while I got stuck on these several Erlang pattern matching problems. Given the module here:

-module(p1).
-export([f2/1]).

f2([A1, A2 | A1]) -> {A2, A1};
f2([A, true | B]) -> {A, B};
f2([A1, A2 | _]) -> {A1,A2}; 
f2([_|B]) -> [B];
f2([A]) -> {A}; 
f2(_) -> nothing_matched.

当我执行 p1:f2([x]),我收到一个空的列表,它是 [] 。我以为它符合第5条款?这个文字也可以是一个原子吗?

and when I execute p1:f2([x]), I received an empty list which is []. I thought it matches the 5th clause? Is that a literal can also be an atom?

当我执行 p1:f2([[a],[b],a]) ,结果是([b],[a]),这意味着它匹配第一个子句。不过我认为[a]和a不一样?一个是一个列表,但另一个是文字?

When I execute p1:f2([[a],[b], a]), the result is ([b], [a]) which means it matches the first clause. However I think [a] and a are not the same thing? One is a list but the other is a literal?

当我执行 p1:f2([2,7 div 3> 2 | [5,3]])它评估为(2,false)。我的意思是为什么 7 div 3> 2 变为假?在其他语言如C或Java是的,我知道 7 div 3 == 2 所以它使这个语句错误。但是在Erlang里呢是一样吗?因为我只是在shell上尝试它,它给了我 2.3333333 .. 大于 2 ,所以它会使这个声明真实。有人可以给出解释吗?

Also when I execute p1:f2([2, 7 div 3 > 2 | [5,3]]) it evaluates to (2, false). I mean why 7 div 3 > 2 gets to be false? In other language such as C or Java Yeah I know 7 div 3 == 2 so it makes this statement false. But is it the same in Erlang? Because I just tried it on shell and it gives me 2.3333333.. which is larger than 2 so it will make this statement true. Can someone gives an explaination?

推荐答案

这是因为 [x] 等于 [x | []] ,所以它匹配 f2([_ | B]) - > [B]; 。你可以看到 B = [] 你的情况。

it is because [x] is equal to [x|[]] so it matches f2([_|B]) -> [B];. As you can see B=[] inn your case.

我想你没有写你想要的去做。在表达式 [A | B] 中,A是列表的第一个元素,而B是列表的其余部分(因此它是一个列表)。这意味着 [1,2,1] 将不匹配 [A1,A2 | A1] ;但是 [[1],2,1] [[a,b],1,a,b] 将会。

I think you didn't write what you want to do. in the expression [A|B], A is the first element of the list, while B is the rest of the list (so it is a list). That means that [1,2,1] will not match [A1, A2 | A1]; but [[1],2,1] or [[a,b],1,a,b] will.

这篇关于模式匹配在Erlang的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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