Some comments to the original question and on this reply.
On 25 July 2012 16:10, Matt Stancliff <
sy...@mindspring.com> wrote:
>
> On Jul 23, 2012, at 2:19 PM, Kurt Miebach wrote:
>
>> what is the correct way to express patterns in function heads and multiple heads? Given this erlang fragment:
>>
>> f1([]) ->
>> ...
>> ok;
>>
>> f1([F|R]) ->
>> ...
>> ok.
>>
>> What would be the LFE equivalent?
The defun macro can be used to define "normal" lisp like functions or
Erlang like multi-clause functions. It all depends on the argument
after the function name if this is just a list of symbols, for example
(a b c d), then it like a lisp function and there is only one clause
and no pattern matching in the head. For example
(defun d-add (a b) (* (+ a b) 2))
If the argument is not a list of symbols then the function contains
(potentially) multiple clauses where each clause is a list where the
first element is a list of argument patterns, the second element is an
optional guard (in a (when <test> <test>)) and the remaining
expressions are the body of the clause. N.B. it is a *LIST* of
arguments even if there is only one. There can of course only be one
clause.
The examples following are of the second type.
> With your example, I prefer:
> (defun f1
> ([()] 'ok)
> ([(f . r)] 'ok))
>
> The empty list can also be represented as '() which would be:
> (defun f1
> (['()] 'ok)
> ([(f . r)] 'ok))
Yes, the empty list can written as either () or '() in a pattern,
which is the same as when it is used in an expression. The reason is
of course that () evaluates to itself ().
This way of writing lists in a pattern has been deprecated though it
is still allowed. The rule is to write the pattern in the same way as
you would write the constructor, in this case (cons f r).
Unfortunately there is no really gentle way of warning about this
mis-pattern. Maybe by warning about the lack of a cons/list/list* and
existence of a '.'. Anyway don't use it.
Again the rule is to write patterns the same way as you would write
the corresponding constructors. The only exceptions are the record
macros which are real macros so have to be used in this way. See the
user_guide.txt.
> LFE also accepts (as you noted):
> (defun f1
> ([()] 'ok)
> ([(cons f r)] 'ok))
>
> All of those are single arity functions equivalent to:
> f1([]) -> ok;
> f1([F|R]) -> ok.
>
> The square brackets are aliases for parens because reading ([()] 'ok) looks nicer than ((()) 'ok).
Yes, the square brackets [] are just alternatives to parentheses and
do the same thing. They are their to make code easier to read.
Robert