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.
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.