Hi I’m learning Erlang via Learn You Some Erlang by Fred Hebert.
And I’ve come across a code that I’m confuse about:
sword(1) -> throw(slice);
sword(2) -> erlang:error(cut_arm);
sword(3) -> exit(cut_leg);
sword(4) -> throw(punch);
sword(5) -> exit(cross_bridge).
talk() -> "blah blah".
black_knight(Attack) when is_function(Attack, 0) ->
try Attack() of
_ -> "None shall pass."
catch
throw:slice -> "It is but a scratch.";
error:cut_arm -> "I've had worse.";
exit:cut_leg -> "Come on you pansy!";
_:_ -> "Just a flesh wound."
end.
So here’s the confusion. I don’t understand sword(#) function. Why are there number as parameter? The function is_function actually check if these function are of arity 0 and apparently all the sword(#) functions are of arity 0.
Also the way to pass in the sword(#) function to the black_knight function is different compare to the talk function.
Here’s how the book pass a sword function and the talk function.
exceptions:black_knight(fun exceptions:talk/0).
vs
exceptions:black_knight(fun() -> exceptions:sword(1) end).
The talk function we just pass the function where as the sword(1) function we have to wrap it with a anonymous function. I don’t get it.
So the questions are:
- Why is passing these
sword(#)different fromtalkfunction. - Why
sword(#)have a number as a parameter? - Why
sword(#)have 0 arity when it seems like it have an arity of 1 (I’m counting the number parameter as a parameter)?
The chapter of the book I’m at.
Thank you for your time.
black_knightfunction,is_function(Attack, 0), it will only match the definition if the function passed in takes 0 parameters. Since talk takes 0 parameters, it can be passed in directly.swordtakes one parameter, so you need to wrap it in an anonymous function that takes 0 parameters before you can pass it in.swordwith1as the argument, you will execute the code in the clausesword(1) ->. If you pass in2as the argument, you will execute the clausesword(2) ->. See this section in Learn You Some Erlang for a more complete description.sworddoes have an arity of 1, so you were counting parameters correctly.