3

I have a very simple question for Prolog programmers. This should be very easy, but I don't have any experience with that language so please help. I am trying to interpret some simple programming language in Prolog. In this language i can have two types of variables - simple variables and array variables. I have a function that calculates the value of given variable:

%calc(+var, +state, -result)

Variable can be either a simple variable like x or array variable like array(ident, index). I don't know how I should write that function in Prolog, so it does different things for regular and array variables. I've come up with something like this:

calc(array(Ident,I), S, R) :- calculating R for array var, !.
calc(Ident, S, R) :- calculating R for regular var.

This works, but there must be some better way.

Tony Babarino
  • 3,355
  • 4
  • 32
  • 44
  • 1
    There isn't really much detail here to say whether there's a much better way, but what you have there looks reasonable. If you want to avoid the cut, you could do `calc(Ident, S, R) :- ( Ident = array(Id, I) -> calc_array(Id, I, S, R) ; calc_var(Ident, S, R)` or something like that. – lurker May 25 '14 at 18:25
  • Thank you! Yes, i was trying to avoid the cut and this looks like a good way to do that. – Tony Babarino May 25 '14 at 18:45

1 Answers1

3

There is a clean way to do it: Use a dedicated wrapper for variables, so you can identify them via pattern matching. For example:

calc(array(Ident,I), S, R)  :- calculating R for array var.
calc(variable(Ident), S, R) :- calculating R for regular var.

I used the functor variable/1 to identify variables.

No !/0 is needed to handle this representation, and you can use your predicates as true relations, i.e. in all directions.

You may need a preprocessing step that wraps variables with a dedicated functor during or after parsing a given program. After that, you have this clean representation and can use pattern matching throughout the remainder of your program.

mat
  • 40,498
  • 3
  • 51
  • 78