Skip to content

Instantly share code, notes, and snippets.

@Steffo99
Created July 20, 2021 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Steffo99/426018f91fd24d93fab610df5366facc to your computer and use it in GitHub Desktop.
Save Steffo99/426018f91fd24d93fab610df5366facc to your computer and use it in GitHub Desktop.
Lunghezza di una lista in prolog
% 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