Alex Rivera | Logout

How can make array in prolog?

Asked 2012-01-29T07:59:56.823
11

I want to make an array in Prolog. How can do it? How can access the elements?

Edit
Report

1 Answer

8

The stadard Prolog way of having (possibly limited in length, non-mutable) arrays is with arg/3 predicate:

11 ?- length(X,4), A =.. [g|X], arg(1,A,a).

X = [a, _G590, _G593, _G596]
A = g(a, _G590, _G593, _G596) 

Yes

12 ?- length(X,4), A =.. [g|X], arg(1,A,a), arg(3,A,c), arg(2,A,b), arg(1,A,d).

No
13 ?- length(X,4), A =.. [g|X], arg(1,A,a), arg(3,A,c), arg(2,A,b), arg(4,A,d).

X = [a, b, c, d]
A = g(a, b, c, d) 

Yes

Bratko ("Prolog programming for artificial intelligence") has the code to solve the classic 8 queens problem using this feature.

Another way to emulate arrays in Prolog is to encode your list as a binary tree, for O(log(n)) access time.

answered 2012-02-23T20:41:58.193

Your Answer