1
votes

I know how to manipulate lists in prolog but I am having trouble with lists of lists, I am studying for an exam and this is one of the practise questions. Can someone help me out with it. All attempts I have made so far were utter failures.

Write a predicate called max2D which takes a list of lists of values as a parameter and returns the maximum of all the values in the list.

Example output: 57

?- max2D([[1,-7,3],[2,10],[19,3],[12]],M). 
M = 19 .
1
I tried many variations, nothing seems to work. I tried using the built in function 'member' but I can't seem to get anywhere with that.The_Stratagem
When you say "the maximum of all the values in the list" it's unclear whether you want a single value, the maximum of all the values in all the lists, or if you want a list of values, the maximum value of each list. This is another reason it would be helpful to include the code you tried as well as what it is the code should do.Daniel Lyons
Here is an example output: 57 ?- max2D([[1,-7,3],[2,10],[19,3],[12]],M). M = 19 . So yes I want just a single value that is the max out of the entire list of lists.The_Stratagem
OK. I'll take a crack at it. You should edit the question with your code so that future readers don't have to read all the comments (which don't support formatted code as well anyway).Daniel Lyons

1 Answers

0
votes

Let's do it in two steps. First, let's get the max of a list:

maxlist([X,Y|Z], Max) :- 
    X > Y -> maxlist([X|Z], Max)
           ; maxlist([Y|Z], Max).
maxlist([X], X).

Looks good:

?- maxlist([1,5,7,3,5], Max).
Max = 7.    

Let's use maplist/3 to apply it over a two dimensional list. The maximum of each maximum will be the overall maximum:

max2D(List, Max) :- 
    maplist(maxlist, List, EachMax),
    max_list(EachMax, Max).

This appears to work:

?- max2D([[1,-7,3],[2,10],[19,3],[12]], X).
X = 19 ;
false.