Binary matcing

32 views
Skip to first unread message

Alexander Kuleshov

unread,
May 12, 2013, 3:44:56 AM5/12/13
to Lisp Flavoured Erlang
Hi all,

I try to write function with lfe which passes binary. How can i match
arg?

For example:

(defun foo (#b 40 rest)

(defun foo ( _ )
'ok)

But i got illegal binary error.

I need something in erlang analog:

foo(<<$40, Rest/binary>>) ->
....;

foo(_) ->
ok.

How can i make it?

Thank you.

rvirding

unread,
May 12, 2013, 1:20:51 PM5/12/13
to lisp-flavo...@googlegroups.com
You need to use another format for defun.


On Sunday, May 12, 2013 9:44:56 AM UTC+2, Alexander Kuleshov wrote:
Hi all,

I try to write function with lfe which passes binary. How can i match
arg?

For example:

(defun foo (#b 40 rest)

(defun foo ( _ )
 'ok)

But i got illegal binary error.

The #b syntax for a binary literal, for example #b(1 2 3). It is equivalent to literal binaries like <<1,2,3>> with byte segments in vanilla erlang.
 
I need something in erlang analog:

foo(<<$40, Rest/binary>>) ->
 ....;

foo(_) ->
  ok.

How can i make it?

To get pattern matching in a function definition you need to use  another format for defun which allows you define multiple clauses with argument patterns and bodies. It looks like:

(defun foo
  (((binary 40 (binary rest))) ...)
  ((...) ...)
  ((_) 'ok))

Each clause has the form

((<argpattern> ...) <body expr> ...)

Note there is no argument list for the whole function here! The "classic" defun syntax is valid but only when giving argument variables with no pattern matching, for example:

(defun bar (a b) (+ a b))

So for example you can define the member function as either:

(defun member (x es)
  (case es
    ((cons x _) 'true)
    ((cons _ es) (member x es))
    (() 'false)))

(defun member
  ((x (cons x . _)) 'true)
  ((x (cons _ es)) (member x es))
  ((_ ()) 'false)))

They are equivalent. The first is more classic lisp style but using pattern matching, while the second is more classic erlang style with clauses.

There is a short description of defun's and binary syntax in the doc/user_guide.txt. There are more tutorials, documentation and examples on the LFE page at http://lfe.github.io/ . Definitely check it out!

Robert

Reply all
Reply to author
Forward
0 new messages