I am trying to find the maximum element in multilayered list (meaning list in list in list...) in Prolog. The thing is, I reviewed all the predicates 1 by 1 and they all work, except for the one that is actually supposed to solve my problem. My approach is to flatten the list (make it single-layered) and the find the maximum element in THAT list. This is my code:
is_list([]).
add([],L,L).
add([X|L1],L2,[X|L3]):-add(L1,L2,L3).
maximum([X|O],M) :- max(O,X,M),!.
max([X|O],Y,M) :- X=<Y, max(O,Y,M).
max([X|O],Y,M) :- X>Y, max(O,X,M).
max([],M,M).
flatten([],[]).
flatten([X|L1],[X|L2]):-not(is_list(X)),!,flatten(L1,L2).
flatten([X|L1],L2):-flatten(X,LX),flatten(L1,LL1),add(LX,LL1,L2).
maximum_in_multilayered_list(L,M):-flatten(L,L1),maximum(L1,N), M is N.
For some reason, I get the following error:
?- maximum_in_multilayered_list([1,[2,3],4],X).
ERROR: Type error: `[]' expected, found `[2,3]' (a list) ("x" must hold one character)
ERROR: In:
ERROR: [13] [2,3]=<1
ERROR: [12] max([[2|...],4],1,_7284) at c:/users/ace_m/documents/prolog/bp.pl:47
ERROR: [11] maximum([1,...|...],_7328) at c:/users/ace_m/documents/prolog/bp.pl:46
ERROR: [10] maximum_in_multilayered_list([1,...|...],_7366) at c:/users/ace_m/documents/prolog/bp.pl:75
ERROR: [9] <user>
Exception: (12) max([[2, 3], 4], 1, _7596) ? creep
I understand that the problem is that I am actually comparing a list of integers with an integer meaning they are incompatible types, but why does it even come to that? What am I doing wrong?