【问题标题】:Error matching Expected type with actual type in function函数中的预期类型与实际类型匹配时出错
【发布时间】:2013-01-27 15:30:42
【问题描述】:

我一直在 getnumfrmcard (xs) 的第一个参数和 (

enter code here
  data Card = Cards (Suit,Face) deriving (Eq)
  data Hand=  Hands[Card]

   straight:: Hand->Bool
   straight (Hands [] )                                     =True
   straight (Hands (x:xs) )                
            | null(xs)==True                          = True
            | getnumfrmcard (x)  < getnumfrmcard (xs) =straight (Hands xs)
            | otherwise                               = False

【问题讨论】:

    标签: haskell


    【解决方案1】:

    此错误表明函数 getnumfrmcard 需要一个类型为 Card 的参数,但给出了 [Card](卡片列表)。罪魁祸首是您拥有getnumfrmcard (xs) 的倒数第二行。如果你将一个列表与(x:xs) 匹配,那么x 将成为列表的头部(单个元素),xs 成为尾部,这是一个列表。所以在

    f []     = []
    f (x:xs) = xs
    
    f [1,2,3] -- [2,3]
    

    xs 绑定到[2,3]

    你可以匹配(Hands (x0:x1:xs)),但你需要决定如何处理一个只有一个参数的列表(我还没想过你真正想要做什么)。

    另请注意:在 Haskell 中,您通常不需要在函数参数周围加上括号,因此您想写 getnumfrmcard xs,而不是 getnumfrmcard (xs)

    【讨论】:

      【解决方案2】:

      另外,如果你想检查你是否有顺子,仅仅检查每张牌是否比下一张低是不够的,它必须低一个

      想到一个更符合 Haskell 的解决方案:

      straight (Hands cards) = and $ zipWith nextStraight cards (tail cards)
         where nextStraight c c' = getnumfrmcard c' == getnumfrmcard c+1
      

      zipWith nextStraight cards (tail cards) 将通过函数nextStraight 组合cards 中的每一对相邻元素(一个检查两张卡片是否具有相邻值的函数)。然后我们通过要求 all 对必须验证谓词来组合生成的布尔列表(因此是 and 函数)。

      当然,必须事先对手牌进行排序才能使此方法起作用,否则将无法检测到某些顺子(例如 [2H,3D,5S,4D,6C])。

      【讨论】:

        【解决方案3】:

        在 haskell 中编码并不那么明显,我会在您的问题中添加更多代码,这样您就不会遇到更多问题 :) 所以我认为基于 Paul 答案的答案可能看起来像这样。

        module Test where
        
        data Card = Cards (Int, Int) deriving (Eq, Ord)
        data Hand = Hands [Card]
        
        straight :: Hand -> Bool
        straight (Hands [] ) = True
        straight (Hands [x0] ) = True
        straight (Hands (x0:x1:xs) )
            | null(xs) == True = True
            | x0 < x1 = straight (Hands xs)
            | otherwise = False
        
        main :: IO ()
        main = print $ straight $ Hands [Cards (5,1), Cards(4,4)]
        

        请随意编辑

        【讨论】:

          猜你喜欢
          • 2015-04-15
          • 1970-01-01
          • 2016-07-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-29
          相关资源
          最近更新 更多