【问题标题】:Haskell extracting from tuples within a list [duplicate]Haskell从列表中的元组中提取[重复]
【发布时间】:2016-03-17 00:40:14
【问题描述】:

我是初学者,任何帮助将不胜感激。我的目标是能够从任何给定的 Film 中提取评分作为 Float,这样我就可以正确地操作数据,例如给出一个“平均评分”电影。

type Title = String
type Director = String
type Year = Int
type Mark = Int
type Rating = (String, Float)

-- Define Film type here
type Film = (Title, Director, Year, [Rating])

典型的电影看起来像

("True Lies", "James Cameron", 1994, [("Dave",3), ("Kevin",10), ("Jo",0)])

我试过了

extractRating :: Film -> [(String, Float)]
extractRating (_, _, _, rating) = rating  

然后像这样调用函数

putStrLn (extractRating "True Lies")

如果它可以帮助你在这里帮助我这个错误转储

haskell.hs:82:21:
Couldn't match type ‘(String, Float)’ with ‘Char’
Expected type: String
  Actual type: [(String, Float)]
In the first argument of ‘putStrLn’, namely
  ‘(extractRating "True Lies")’
In a stmt of a 'do' block: putStrLn (extractRating "True Lies")

haskell.hs:82:35:
Couldn't match type ‘[Char]’
               with ‘(Title, Director, Year, [Rating])’
Expected type: Film
  Actual type: [Char]
In the first argument of ‘extractRating’, namely ‘"True Lies"’
In the first argument of ‘putStrLn’, namely
  ‘(extractRating "True Lies")’
In a stmt of a 'do' block: putStrLn (extractRating "True Lies")

【问题讨论】:

  • 还是那个电影数据库练习??
  • 是的,仍然。你每年都会从像我这样的人那里收到这些帖子,认为这是一种传统;)
  • 您将String 传递给extractRating 函数,该函数需要Film 类型作为唯一参数。此外,putStrLn 需要 String。也许您想改用print
  • 这个练习需要你使用元组吗?因为这更适合 Record 类型。
  • 我很难为此幽默。这确实是一个糟糕的问题,我找不到任何借口。不管这个练习有多糟糕,你为什么不只是摆弄一下 GHCi 直到你得到它?真的没那么难。

标签: haskell tuples


【解决方案1】:

我不能发表评论,但我强烈建议查看数据关键字和模式匹配,而不是使用元组。

PS:经过编辑以提供更多帮助。无论如何,我看到的问题是“真实的谎言”。 extractRating 的输入是电影类型,当你给它一个字符串时。解决此问题的一种方法是,不要将输入设为电影,只需将其更改为字符串,然后根据给定字符串查找任何匹配项以返回评分。

【讨论】:

  • 嗯,是的,应该使用data 和模式匹配。但这真的不能回答问题,也不能帮助 OP 解决手头的问题,也不能解决我们目前遇到的这些愚蠢的电影数据库问题。 (而且 FWIW,我什至不确定我是否不赞成使用元组而不是 data 的练习——这不是很好的风格,但对于初学者来说,这似乎是一个合理的简化。)
  • 我尽量不给太多,因为这似乎是家庭作业,这使得无论如何都无法更改这些电影数据库问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-29
  • 1970-01-01
  • 1970-01-01
  • 2018-08-30
  • 2017-04-20
  • 2018-05-18
相关资源
最近更新 更多