What does this Erlang statement do?
I have this Erlang code:
not lists:any(fun(Condition) ->Condition(Message) end, Conditions).
Can anyone please explain the entire statem开发者_运维百科ent in layman's terms? For your information Condition
is a function, Conditions
is an array. What does fun(Condition) ->Condition(Message) end
mean? As well as meaning of not lists:any
.
fun(Condition) ->Condition(Message) end
is a lambda function that applies the function Condition
to the value of Message
(taken as a closure on the surrounding code).
lists:any
is a function that takes a predicate and a list of values, and calls the predicate on each value in turn, and returns the atom true
if any of the predicate calls do.
Overall, the result is the atom true
if none of the Condition
functions in the list Conditions
return true
for the Message
value.
EDIT -- add documentation for lists:any
any(Pred, List) -> bool()
Types:
Pred = fun(Elem) -> bool()
Elem = term()
List = [term()]
Returns true if Pred(Elem)
returns true for at least one element Elem
in List.
Condition is something that takes a message and returns a boolean if it meets some criteria.
The code goes through the list of conditions and if any of them say true then it returns false, and if all of them say false it says true.
Roughly translated to verbose pseudo-Python:
def not_lists_any(Message,Conditions):
for Condition in Conditions:
if Condition(Message):
return False
return True
One step behind syntax and stdlib description which you have in other answers:
This code looks very much like an Erlang implementation of chain-of-responsibility design pattern. The message (in OOP sense of the word) "traverses" all possible handlers (functions from Conditions
array) until someone can handle it. By the author's convention, the one which handles the message returns true
(otherwise false
), so if nobody could handle the message the result of your expression as a whole is true
:
% this is your code wrapped in a function
dispatch(Message, Handlers) ->
not lists:any(fun(Condition) ->Condition(Message) end, Handlers).
It may be used like this:
CantHandle = dispatch(Event, Handlers),
if CantHandle->throw(cannot_handle); true->ok end.
精彩评论