繁体   English   中英

Haskell:比较元组列表中的元素

[英]Haskell: comparing elements in a tuple list

项目说明:

给定5个元素元组的列表(例如[(String,Int,String,Int,Int)] ),如果该元素的第1个元素表示工人的姓名,第4个元素表示其薪水,必须创建一个函数(称为biggestPay ),该函数给出薪水最高的工人的姓名。

限制条件:

继《学好Haskell》这本书之后,我只能使用(包括)高阶函数和前奏函数之前的所有内容。

到目前为止我的作品:

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

我的想法是比较所有工人的薪水并将他们的名字存储在列表中,然后最后,由于列表的最后一个元素是薪水最高的工人,因此我会删除所有其他元素以仅获得该工人的名字。

但是,当我尝试将此函数加载到GHCI中时,出现以下错误:

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 ...是无效的Haskell语法,但是您可以这样使用let

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

但是,您的方法还有很多其他问题。 例如,此代码片段:

getPay(getPayList y:xs)

被Haskell解释为

getPay( (getPayList y) : xs)

由于y是整数,并且getPayList对元组列表进行操作,因此不进行类型检查。

暗示

如何查看LYAH如何引入最大功能:

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 

对该功能可能有一个简单的调整,它将为您提供biggestPay函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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