tags:

views:

251

answers:

2

I want to do a selective receive where a record property needs to be matched, but whatever syntax I try, I get an "illegal pattern" message.

loop(State) ->
  receive
    {response, State#s.reference} -> do_something()
  end.

Is this not possible?

+6  A: 
loop(State) ->
    receive
       {response, R} when R =:= State#s.reference ->
             do_something()
    end.
Maxim 'Zert' Treskin
+12  A: 

Just an alternative which uses pattern matching:

loop(#s{reference = Reference} = State) ->
  receive
    {response, Reference} ->
      do_something()
  end.
Zed
This is what I was really looking for.
John Galt
It's a little baffling, though. Reference in the loop line looks like it's being bound to State#s.reference, yet it's on the rhs.
John Galt
That's because that is a different kind of equal sign :) This is "syntactic sugar" for records, but your equal sign is Erlang's binding operator.
Zed
Ok, good. I just wanted to make sure that was the case, and there wasn't some deeper principle I was missing. Even when I wrote my original, I knew it was wrong for the reason you gave, because that syntax isn't for binding, but I was trying to illustrate the gist. I knew I had seen record pattern matching like this example before!
John Galt
Forgot to add that you can use this form to match on values, e.g.: `loop(#s{reference = undefined} = State) ->`
Zed