-
-
Save Steffo99/426018f91fd24d93fab610df5366facc to your computer and use it in GitHub Desktop.
Lunghezza di una lista in prolog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% Caso base: se la lista è vuota, la sua lunghezza (RESULT) è pari alla lunghezza accumulata finora (PREC) | |
len([], PREC, RESULT) :- | |
RESULT is PREC, | |
% Ferma qui la ricorsione. | |
!. | |
% Caso iterativo: se la lista contiene elementi, togli il primo (_), aggiungi 1 alla lunghezza accumulata (PREC + 1) e calcola la lunghezza della parte restante (TAIL) | |
len([_ | TAIL], PREC, RESULT) :- | |
len(TAIL, PREC + 1, RESULT). | |
% Dolcificante sintattico: chiamare manualmente len([1, 2, 3], 0, RESULT) è scomodo, quindi se ci sono solo due argomenti assumi che PREC sia 0 | |
len(LIST, RESULT) :- | |
len(LIST, 0, RESULT) | |
% ?- len([1, 2, 3], WHAT). | |
% WHAT = 3. | |
% ?- len(WHAT, 3). | |
% WHAT = [_, _, _]. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment