Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- %3.2.1 Write the predicate
- % append3(L1, L2, L3, R), which achieves the concatenation of 3 lists.
- append3(L1, L2, L3, R):- append(L2, L3,R1), append(L1, R1,R).
- %3.2.2 Write a predicate which adds an element at the beginning of a list.
- %
- addEl(X, L, [X|L]). % X e head-ul rezultatului, lista initiala e tail-ul rezultatlui
- %3.2.3 Write a predicate which computes the sum of the elements of a list of integers.
- %
- sumEL([H|T], R) :- sumEl(T,R1), %1. mergi pana la finalul listei
- R is R1+H. % 3. R+= cate un element de la final spre inceput
- sumEl([],0). %2. se initializeaza R cu 0
- %3.3.1 Write a predicate which takes as input a list of integers, L,
- %and produces two lists: the list containing the even elements from L
- %and the list of odd elements from L.
- separate([H|T], [H|Even] ,Odd):- 0 is H mod 2, % primu element e par, o sa il punem in Even cand se termina apelul
- separate(T,Even,Odd). % mergem mai departe pe restul litei
- separate([H|T],Even,[H|Odd]):- 1 is H mod 2, % e impar
- separate(T,Even,Odd).
- separate([],[],[]). % am ajuns la finalul listei, initializam rezultatele cu lista vida, de acum incep apelurile sa
- % se termine si se pun elementele in liste ( de la sfarsit spre inceput)
- %3.3.2 Write a predicate which removes all the duplicate elements in a list
- %(keep either the first or the last occurrence).
- %
- remove_dup([H|T], R):-member(H,T), %daca primul element se gaseste in restul listei, nu il punem in rezultat
- remove_dup(T,R),!. %trecem la urmatoarele elemente
- remove_dup([H|T],[H|R]):-remove_dup(T,R). %daca nu, trecem la urmatoarele elemente,
- %dar punem elementul in rezultat
- remove_dup([],[]). %cand am ajuns la sfarsit, initializam rezultatul cu []
- %3.3.3. Write a predicate which replaces
- %all the occurrences of element K with NewK in list L.
- %
- replace([H|T], K, NewK, [NewK|R]):- H=K, %primu el. din lista e acelasi cu K, punem NewK in rezultat
- replace(T,K,NewK,R). %trecem mai departe
- replace([H|T],K,NewK,[H|R]):- not(H=K), % nu trebuie neaparat scris ca la if else
- % punem elementul il rezultat
- replace(T,K,NewK,R).
- replace([],_,_,[]). % _ inseamna ca nu conteaza ce e acolo ca nu folosesti nicaieri
- %3.3.4. Write a predicate which deletes every Kth element from a list.
- %
- drop_k([H|T], K, [H|R], PosCur):- not(0 is PosCur mod K),!, %nu trebuie sters, il punem in rezultat
- PosCur1 is PosCur+1, %calculam pozitia urmatoare
- drop_k(T,K,R,PosCur1).
- drop_k([_|T], K, R, PosCur):- PosCur1 is PosCur +1, %nu il punem pe H in rezultat
- drop_k(T,K,R,PosCur1).
- drop_k([],_,[],_).
- % drop_k([1,2,3,4,5],2,R,1).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement