From af3b2f8887519692192a8eef6d8ce57d2a9b2be9 Mon Sep 17 00:00:00 2001 From: Ziad Arafat Date: Tue, 2 May 2023 19:22:21 -0600 Subject: [PATCH] Finished first two problems --- PA009/hw5_arafat_ziad.pl | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 PA009/hw5_arafat_ziad.pl diff --git a/PA009/hw5_arafat_ziad.pl b/PA009/hw5_arafat_ziad.pl new file mode 100644 index 0000000..1ce32cd --- /dev/null +++ b/PA009/hw5_arafat_ziad.pl @@ -0,0 +1,28 @@ +% 1. +% Without tail recursion version +% listLen([],0). +% listLen([_|ListTail],N) :- listLen(ListTail,X), N is X+1. + +% This version uses an accumulator parameter to store intermediate values +% This allows us to only compute the result after the last call is completed. +% Tail recursion is more efficient because they don't need to keep track of as +% much memory as the stack of calls grows. +leng([_|T],A,L) :- Anew is A+1, leng(T,Anew,L). % recursive case +leng([],A,A). % Base case + +% Helper function to meet parameter requirements +listLen(Length, List) :- leng(List,0,Length). + + +% 2. +% When we reach the kth element we unify the first argument with the tail +% Thus returning the tail. +dropK(Tail, [_|Tail], 1). + +% If we haven't reached it yet we decrement the index and call again with the tail +% We set the result to be the combination of the Head and the result of the next call. +dropK(Result, [Head|Tail], RemoveIndex) :- RemoveIndex > 1, + NewIndex is RemoveIndex - 1, + dropK(X, Tail, NewIndex), Result = [Head|X]. + +% 3.