高阶函数中变量的绑定和匹配问题

本文探讨了Erlang中高阶函数的测试方法,指出了直接在函数内部进行模式匹配可能导致的问题,并给出了正确的实现方式。通过具体的例子说明如何避免变量导入规则导致的匹配错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一直一来没有留意到这个问题,今天偶尔在blog上看到,就标记一下,别让自己忘记了。

文章在 http://easyerl.blogspot.com/2007/10/high-order-functions-must-be-tested.html

测试代码如下:
[code]1> Filter = fun(Elem) -> fun({Elem, _, _}) -> true; (_) -> false end end.
#Fun<erl_eval.6.49591080>
2> C = Filter(cpu).
#Fun<erl_eval.6.49591080>
3> C({test, t, t}).
true % this should have been false ...[/code]

按理来说,C应该等同与一个这样的函数:
[code]fun({cpu, _, _}) -> true; (_) -> false end.[/code]
这样
C({test, t, t}) 应该返回 false

作者指出,参考 http://www.erlang.org/doc/programming_examples/funs.html#2.4,有一段如下文字:
[quote]The rules for importing variables into a fun has the consequence that certain pattern matching operations have to be moved into guard expressions and cannot be written in the head of the fun. [/quote]

因此应该用
[code]f(...) ->
Y = ...
map(fun(X) when X == Y ->
;
(_) ->
...
end, ...)
...[/code]
取代
[code]f(...) ->
Y = ...
map(fun(Y) ->
;
(_) ->
...
end, ...)
...[/code]

因此正确做法是
[code]Filter = fun(Elem) ->
fun({X, _, _}) when X == Elem -> true; (_) false end
end.[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值