【问题标题】:Maybe Int type error [duplicate]也许是 Int 类型错误 [重复]
【发布时间】:2017-05-12 07:21:14
【问题描述】:

我得到一个类型错误,因为我试图递归地添加一个 Maybe int int 函数 rankP 如下所示。因为 rankP 的返回类型是 Maybe Int,而 rankC 的类型是 Ints 的元组,它告诉我不能将 Int 与 Maybe Int 相加。

type Prog = [Cmd]

data Cmd = LD Int
    | ADD
    | MULT
    | DUP
    | INC
    | SWAP
    | POP Int
    deriving Show       
type Stack = [Int]
type D = Stack -> Maybe Stack
type Rank = Int
type CmdRank = (Int,Int)


rankC :: Cmd -> CmdRank
rankC (LD _) = (0,1)
rankC ADD = (2,1)
rankC MULT = (2,1)
rankC DUP = (1,2)
rankC INC = (1,1)
rankC SWAP = (2,2)
rankC (POP x) = (x,0)


rankP :: Prog -> Maybe Rank
rankP [] = Nothing
rankP [x] = Just (snd(rankC x) - fst(rankC x))
rankP (x:xs) = if ((Just (snd(rankC x) - fst(rankC x)) + rankP xs) < 0) then Nothing
                    else Just (snd(rankC x) - fst(rankC x)) + (rankP xs)

这是我收到的错误:

hw3.hs:43:64:
    Couldn't match expected type `Int' with actual type `Maybe Rank'
    In the return type of a call of `rankP'
    In the first argument of `Just', namely `(rankP xs)'
    In the second argument of `(+)', namely `Just (rankP xs)'
Failed, modules loaded: none.

【问题讨论】:

  • 你想要完成什么,你的问题是什么?
  • 哪里出错了?

标签: haskell


【解决方案1】:

我得到一个稍微不同的错误:

No instance for (Num (Maybe Int)) arising from a use of ‘+’
In the first argument of ‘(<)’, namely
  ‘(Just (snd (rankC x) - fst (rankC x)) + rankP xs)’
In the expression:
  ((Just (snd (rankC x) - fst (rankC x)) + rankP xs) < 0)
In the expression:
  if ((Just (snd (rankC x) - fst (rankC x)) + rankP xs) < 0) then
      Nothing
  else
      Just (snd (rankC x) - fst (rankC x)) + (rankP xs)

但是,请注意,在

(Just (snd(rankC x) - fst(rankC x)) + rankP xs) < 0

您尝试在两个Maybe Rank 对象上使用+,并将结果与​​&lt; 与0 进行比较。这些都不起作用。

从您的代码中,您似乎正在尝试“提取”Maybe Rank 的值;请参阅this question

【讨论】:

    【解决方案2】:

    问题在于,当您确实需要在进行任何数学运算之前从 Maybe Rank 中提取 Rank 时,您正尝试使用 Maybe Rank 进行算术运算。一种方法是直接手动:

    rankP (x:xs) = if y == Nothing
                   then Nothing
                   else let Just y' = y in
                        if snd(rankC x) - fst(rankC x) + y' < 0
                        then Nothing
                        else Just (snd(rankC x) - fst(rankC x) + y')
        where y = rankP xs
    

    当您开始了解Maybe 的一元属性时,肯定有更优雅的方法可以做到这一点。我自己还没有在这些方面提供太多帮助。

    【讨论】:

      猜你喜欢
      • 2016-01-04
      • 2016-10-28
      • 2015-07-31
      • 1970-01-01
      • 2021-04-14
      • 2022-09-27
      • 2012-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多