Tamil Selvan
Tamil Selvan

Reputation: 75

error while creating a custom max function haskell

I was trying to create max function to compare a list of n dimensional coordinates based on the values of 1st coordinate

max :: [(Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int)] -> (Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int)
max []                               = (0,0,0,0,0,0,0,0,0,0,0,0,0,0)
max [(ar,a,b,c,d,e,f,g,h,i,j,k,l,m)] = (ar,a,b,c,d,e,f,g,h,i,j,k,l,m)
max (ar,a,b,c,d,e,f,g,h,i,j,k,l,m):(ar1,a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1,m1):tail
    | ar > ar1                       = max (ar,a,b,c,d,e,f,g,h,i,j,k,l,m):tail
    | otherwise                      = max (ar1,a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1,m1):tail

But I am getting error in 4th line:

1.hs:81:1: error: Parse error in pattern: max
    |
81 | max (ar,a,b,c,d,e,f,g,h,i,j,k,l,m): 
(ar1,a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1,m1):tail    | 
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Upvotes: 0

Views: 66

Answers (2)

talex
talex

Reputation: 20455

You can use this code

import Data.List(maximumBy)
import Data.Ord(comparing)

max2 :: [(Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int)] -> (Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int)
max2 [] = (0,0,0,0,0,0,0,0,0,0,0,0,0,0) 
max2 x  = maximumBy cmp x   
    where 
       cmp = comparing first
       first (v,_,_,_,_,_,_,_,_,_,_,_,_,_) = v

Upvotes: 2

shree.pat18
shree.pat18

Reputation: 21757

A couple of things to fix it:

  1. In your case for multi-item list, surround the argument with brackets i.e.

max ((ar,a,b,c,d,e,f,g,h,i,j,k,l,m):ar1,a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1,m1):tail)

  1. When you make the recursive call, qualify your function name. Else, you will end up with ambiguity between Prelude.max and your own function. I'd recommend changing the function name as the easy solution.

Taken together, you should see something like this:

max2 :: [(Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int)] -> (Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int)
max2 []                               = (0,0,0,0,0,0,0,0,0,0,0,0,0,0)
max2 [(ar,a,b,c,d,e,f,g,h,i,j,k,l,m)] = (ar,a,b,c,d,e,f,g,h,i,j,k,l,m)
max2 ((ar,a,b,c,d,e,f,g,h,i,j,k,l,m):(ar1,a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1,m1):tail)
    | ar > ar1                       = max2 $ (ar,a,b,c,d,e,f,g,h,i,j,k,l,m):tail
    | otherwise                      = max2 $ (ar1,a1,b1,c1,d1,e1,f1,g1,h1,i1,j1,k1,l1,m1):tail

Upvotes: 4

Related Questions