|
| 1 | +#+TITLE: Lists |
| 2 | + |
| 3 | + A list is either empty or it is composed of a first element (head) and a tail, |
| 4 | + which is a list itself. In λProlog, we represent the empty list by the atom |
| 5 | + =[]= and a non-empty list by a term =[H|T]= where =H= denotes the head and =T= |
| 6 | + denotes the tail. |
| 7 | + |
| 8 | +* 1.01 (*) Find the last element of a list. |
| 9 | + |
| 10 | +Example: |
| 11 | + |
| 12 | +#+begin_src teyjus-edit |
| 13 | +> list.last [1,2,3,4] X. |
| 14 | +X = some 4 |
| 15 | +#+end_src |
| 16 | + |
| 17 | +* 1.02 (*) Find the last but one element of a list. |
| 18 | + |
| 19 | +Example: |
| 20 | + |
| 21 | +#+begin_src teyjus-edit |
| 22 | +> list.second-last [1,2,3,4] X. |
| 23 | + |
| 24 | +Success: |
| 25 | + X = some 4 |
| 26 | +#+end_src |
| 27 | + |
| 28 | +* 1.03 (*) Find the =n='th element of a list. |
| 29 | + |
| 30 | +The first element in the list is number 0. |
| 31 | +Example: |
| 32 | + |
| 33 | +#+begin_src teyjus-edit |
| 34 | +> list.nth [1,2,3,4,5] 2 X. |
| 35 | + |
| 36 | +Success: |
| 37 | + X = some 3 |
| 38 | +#+end_src |
| 39 | + |
| 40 | +* 1.04 (*) Find the number of elements of a list. |
| 41 | + |
| 42 | +The predicate should work with the arguments in any mode. |
| 43 | + |
| 44 | +#+begin_src teyjus-edit |
| 45 | +> list.len [1,2,3,4] X. |
| 46 | + |
| 47 | +Success: |
| 48 | + X = 4 |
| 49 | + |
| 50 | +> list.len L 4. |
| 51 | + |
| 52 | +Success: |
| 53 | + L = [X0, X1, X2, X3] |
| 54 | + |
| 55 | +> list.len L X. |
| 56 | + |
| 57 | +Success: |
| 58 | + L = [] |
| 59 | + X = 0 |
| 60 | + |
| 61 | +More? (Y/n) |
| 62 | +y |
| 63 | + |
| 64 | +Success: |
| 65 | + L = [X0] |
| 66 | + X = 1 |
| 67 | + |
| 68 | +More? (Y/n) |
| 69 | +y |
| 70 | + |
| 71 | +Success: |
| 72 | + L = [X0, X1] |
| 73 | + X = 2 |
| 74 | +#+end_src |
| 75 | + |
| 76 | +* 1.05 (*) Reverse a list. |
| 77 | + |
| 78 | +The predicate should work both ways. |
| 79 | + |
| 80 | +#+begin_src teyjus-edit |
| 81 | +> list.reverse [1,2,3,4] X. |
| 82 | + |
| 83 | +Success: |
| 84 | + X = [4,3,2,1] |
| 85 | + |
| 86 | +> list.reverse X [4,3,2,1]. |
| 87 | + |
| 88 | +Success: |
| 89 | + X = [1,2,3,4] |
| 90 | +#+end_src |
| 91 | + |
| 92 | +* 1.06 (*) Find out whether a list is a palindrome. |
| 93 | + |
| 94 | +A palindrome can be read forward or backward; e.g. ["x","a","m","a","x"]. |
0 commit comments