So I'm doing some Prolog in SWI-Prolog and I've come across a little snag. I must create a list of cubes, given an input list. The code I currently have is
cubes([Head|Tail],Cubes) :-
cubes([Head|Tail],Cubes,[]).
cubes([Head|Tail],Cubes,ActualCubes) :-
X is Head^3,
append(ActualCubes,[X],NewCubes),
cubes(Tail,Cubes,NewCubes).
cubes([Tail],Cubes,ActualCubes) :-
X is Tail^3,
append(ActualCubes,[X],NewCubes),
Cubes is NewCubes.
When I run that it gives an error, specifically...
ERROR: '.'/2: Type error: `[]' expected, found `[8]' ("x" must hold one character)
Exception: (7) cbList([1, 2], _G296, []) ? creep
I'm not entirely sure why this error is occurring but it seems to happen around the very last line, Cubes is NewCubes. Any help is appreciated :)
First, you're making different cubes
predicates with differing numbers of arguments. This is bound to cause both conceptual and syntactical problems, so at that point, re-think what you're doing. In this case, try to expand the ways you can use pattern matching and recursion:
cubes([],[]).
cubes([H|T], [Y|Z]):-
Y is H*H*H,
cubes(T,Z).
betterCubes([],[]).
betterCubes([H|T], [Y|Z]):-
(
var(Y) , nonvar(H) -> Y is H*H*H
; nonvar(Y) , var(H) -> H is Y**(1.0/3.0)
; nonvar(Y) , nonvar(H) -> H*H*H =:= Y
),
betterCubes(T,Z).