【问题标题】:Haskell: comparing elements in a tuple listHaskell:比较元组列表中的元素
【发布时间】:2015-10-26 11:48:38
【问题描述】:

项目说明:

给定一个包含 5 个元素元组的列表(例如 [(String,Int,String,Int,Int)]),元组的第一个元素代表工人的姓名,第四个元素代表他/她的薪水,我必须创建一个函数(称为 @ 987654322@),它给出了薪水最高的工人的名字。

限制:

按照“Learn you a Haskell for a great good”一书,我只能使用(包括)高阶函数和前奏函数的所有内容。

到目前为止我的作品:

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.

【问题讨论】:

  • is 是什么意思?

标签: list haskell comparison tuples


【解决方案1】:

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 函数。

【讨论】:

  • 嗯,我似乎无法弄清楚调整,但例如,如果我首先使用 getName 从作品中删除所有名称,他们会使用 getPay 删除所有薪水,然后使用最大值包含所有薪水的列表(使用 getPay 创建),获取该号码的索引,然后返回具有相同索引的名称,它会工作吗?还是我把事情复杂化了?
  • 如果你只是改变我用“改变这一行”标记的那行,你会得到一个函数[(String,Int,String,Int,Int)] -&gt; (String,Int,String,Int,Int),它返回最高工资的元组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-01
  • 2021-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-28
相关资源
最近更新 更多