简体   繁体   中英

Haskell: comparing elements in a tuple list

Explanation of the project :

Being given a list of 5 element tuples (eg. [(String,Int,String,Int,Int)] ) , were the 1st element of the tuple represents the name of a worker and the 4th element represents his/her paycheck, I must make a function (called biggestPay ) that gives the name of the worker with the biggest paycheck.

Restrictions:

Following the book "Learn you a Haskell for a great good" I can only use everything up to (including) Higher Order Functions and Prelude functions.

My works so far:

getPay :: (String,Int,String,Int,Int) -> Int
getPay (_,_,_,a,_) = a 

getName ::(String,Int,String,Int,Int) -> String
getName (a,_,_,_,_) = a

getPayList :: [(String,Int,String,Int,Int)] -> String
getPayList [] = [] 
getPayList xs = [ x | y <- [0..(length xs)-1] , 
    if getPay(getPayList y:xs) >= getPay(getPayList (y+1):xs) 
    then x is getName(getPayList y:xs) 
    else x is getName(getPayList (y+1):xs)]

biggestPay :: [String] -> String
biggestPay [] = []
biggestPay xs = drop ((length xs) -1) xs

My idea was compare the paychecks of all the workers and store their name in a list and then finally since the last element of the list would be the worker with the biggest paycheck I would drop all the other elements to get that worker's name only.

However when I try to load this function into GHCI I get these errors:

ghci> :l Pay.hs
[1 of 1] Compiling Main             ( Pay.hs, interpreted )

Pay.hs:9:19: Not in scope: `x'

Pay.hs:11:22: Not in scope: `x'

Pat.hs:11:24:
    Not in scope: `is'
    Perhaps you meant one of these:
      `xs' (line 9), `id' (imported from Prelude)

Pay.hs:12:22: Not in scope: `x'

Pay.hs:12:24:
    Not in scope: `is'
    Perhaps you meant one of these:
      `xs' (line 9), `id' (imported from Prelude)
Failed, modules loaded: none.

x is ... isn't valid Haskell syntax, but you can use let like this:

getPayList (x:xs) = [ x | y <- [...]
                        , let x = if ... then ... else ... ]

However, there are a lot of other problems with your approach. For instance, this code fragment:

getPay(getPayList y:xs)

is interpreted by Haskell as

getPay( (getPayList y) : xs)

which doesn't type check since y is an integer and getPayList operates on a list of tuples.

Hint

How about looking at how LYAH introduces the maximum function:

http://learnyouahaskell.com/recursion

maximum' :: (Ord a) => [a] -> a  
maximum' [] = error "maximum of empty list"  
maximum' [x] = x  
maximum' (x:xs)   
    | x > maxTail = x             -- change this line
    | otherwise = maxTail  
    where maxTail = maximum' xs 

Perhaps there is a simple tweak to that function which will give you the biggestPay function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM