/* Arrays in Picat. From Rosetta Code http://rosettacode.org/wiki/Arrays """ This task is about arrays. [...] In this task, the goal is to show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element. (if available, show both fixed-length arrays and dynamic arrays, pushing a value into it.) """ Note: Picat has support both of arrays and lists with much syntax in common. Arrays are often faster to access etc, and lists are more dynamic. Here we show some example of both arrays and lists. This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import util. % import cp. main => go. go => % % Arrays % println("Arrays"), Len = 10, A = new_array(Len), bind_vars(A,0), % set all values to 0 println(A), A[1] := 1, % assign a value println(A), println(a1=A[1]), % (re)assign a value foreach(I in 1..Len) A[I] := 2 end, println(A), % 2D array A2 = new_array(4,4), foreach(I in 1..4, J in 1..4) A2[I,J] := (I-1)*4+J end, foreach(Row in A2) writeln(Row) end, println(rows=A2.rows()), % from util.pi println(columns=A2.rows()), % from util.pi println(diagonal1=A2.diagonal1()), % from util.pi println(diagonal2=A2.diagonal2()), % from util.pi % arrays don't increment automatically % (here we just catch and write the exception: "out_of_bound") catch(writeln(A[Len+1]),E, handle_exception(E)), nl, % % Lists % println("Lists"), % Define the lists (with unitialized variables) L = new_list(Len), println(L), % Assign the first element to 1 L[1] := 1, println(L), % Assign to all elements foreach(I in 1..Len) L[I] := I end, println(L), % Append an element last L := L ++ [1], println(L), L := delete(L,L[1]), println(L), L := [L[I] : I in 2..L.length], % remove first element println(L), % insert an element last L := insert(L,L.length+1, 99), println(L), % extract odd elements println([El : El in L, El mod 2==1]), println([first=L.first(), second=L.second(),last=L.last()]), nl. handle_exception(E) => writeln(exception=E).