Alex Poovathingal
Alex Poovathingal

Reputation: 166

Erlang : Conditions involving user-defined functions on objects that are not pattern-matchable

In an Erlang code, I am using a dictionary like data structure which has a list of {tag, value}. eg: {robot, [{x-pos, 50}, {y-pos, 100}, {speed, 10}]. The number of elements in the list or it's order cannot be predicted. I have written functions that will traverse the list to find values of each parameter like get_xpos, get_ypos ,etc.

I want to write a function which should behave like this

function(MyTuple) when get_xpos (MyTuple) > 50 -> stop;
function(MyTuple) when get_ypos (MyTuple) < 50 -> forward.

As user-defined functions are not permitted in guards or if in Erlang, this is not possible. As there are many conditions like this, it won't be elegant to write case statements for each of these conditions. Is there any better way to do this?

Upvotes: 2

Views: 166

Answers (1)

Isac
Isac

Reputation: 2068

You could do this:

aux_fun(TupleList) -> fun(get_xpos(TupleList), get_ypos(TupleList)).

fun(XPos, YPos) when XPos > 50 -> stop;
fun(XPos, YPos) when YPos < 50 -> forward.

Upvotes: 1

Related Questions