Perfect Square in Prolog
Go to solution
Solved by elpiop,
10 hours ago, BuckGup said:Looking for some help with a program designed to accept a list and return only the perfect squares in it. As well as return the length of the new list of how many perfect squares were found. Here is the existing code
is_perfect(X) :- floor(sqrt(X))^2 =:= X. perfect_squares([],[],0). perfect_squares([H|T],Y,Z) :- is_perfect(H), length(Y,Z), append(H,Y,Y). perfect_squares([H|T],Y,Z) :- perfect_squares(T,Y,Z), length(Y,Z).I can trace it in the debugger and it works properly but it's not appending to Y so it returns the length to be zero and not any of the found squares.
I am getting a stack overflow with the code you posted. Tried to figure it out but unfortunately can't remember prolog very well lol
I did write a solution using findall, if that helps at all:
is_perfect(X) :- floor(sqrt(X))^2 =:= X. perfect_squares([], [], 0). perfect_squares(Lst, Bag, Count) :- findall(X, (member(X, Lst), is_perfect(X)), Bag), length(Bag,Count).
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now