【问题标题】:"Pattern syntax in expression context: _" when using map使用地图时的“表达式上下文中的模式语法:_”
【发布时间】:2014-04-01 21:07:24
【问题描述】:

我有这段代码,它将有条件地更新(或添加)一个元组到一个元组列表中。我得到了上述错误

updateTuple :: String -> String -> Int -> [Film] -> String
updateTuple userName requestedTitle newRating ((Film title _ _ ratings):restOfFilms)
    | requestedTitle == title = map (\ rating -> if rating == (userName,_) then (userName,newRating) else rating) ratings
    | otherwise = updateTuple userName requestedTitle newRating restOfFilms

【问题讨论】:

  • 该消息非常具有描述性:if rating == (userName,_) 中的 _ 对我和编译器都没有意义。
  • 所以我不能使用通配符?
  • @user3365968 您不能在比较中使用通配符,只有在 case 语句中的 =-> 的左侧模式匹配或绑定中的 <- 的左侧模式匹配时.你真正应该做的是if fst rating == userName then ...
  • 顺便说一句,您的函数的类型签名没有意义:您将评级列表映射到元组列表,而签名声明您的函数返回String

标签: haskell map tuples


【解决方案1】:

正如@bheklilr 和@Nikita Volkov 所指出的,问题就在这里:

| requestedTitle == title = map (\ rating -> if rating == (userName,_) then (userName,newRating) else rating) ratings

另一种方法是使用@-syntax 来解构rating 变量:

| requestedTitle == title = map (\rating@(ruser,_) -> if ruser == userName then ... else rating)

【讨论】:

  • | requestedTitle == title = map (\rating -> if fst rating == userName then (userName, newRating) else rating) ratings 我收到一个错误,它需要一个 Char 吗? @user5402
  • @user5402 问题是他的函数的类型签名将结果类型定义为String,而映射结果是一个元组列表。由于String 只是Chars 列表的别名,这就解释了他得到的错误。
【解决方案2】:

问题在于这个 lambda:

\rating -> if rating == (userName,_) then (userName,newRating) else rating

您在表达式上下文中使用通配符,这对编译器没有意义,因为通配符只能在模式匹配上下文中使用。

我猜你打算这样做:

\rating@(userName', _) -> 
  if userName' == userName then (userName,newRating) else rating

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    相关资源
    最近更新 更多