首页 > 解决方案 > 如何使函数具有不同数量的参数

问题描述

buyItem :: Hero -> Item -> Hero

buyItem (Mage n Wealth Gold) item1 = (Mage n Wealth item1)

buyItem (Warrior a item)
    | enough (Warrior a c) >= cost item = (Warrior a c++item)
    | otherwise = (Warrior a c)

buyItem (Mage a b c) item
    | enough (Mage a b c) >= cost item = (Mage a b item)
    | otherwise = (Mage a b c)

RPGdefs.hs:136:1: error:
    Equations for ‘buyItem’ have different numbers of arguments
      RPGdefs.hs:136:1-58
      RPGdefs.hs:(137,1)-(139,31)
    |
136 | buyItem (Mage n Wealth Gold) item1 = (Mage n Wealth item1)
    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...
Failed, no modules loaded.

标签: haskell

解决方案


你这里有一个错字:

buyItem (Warrior a item)

应该是这样的:

buyItem (Warrior a) item

当您编写(Warrior a item)时,这意味着它item是 的一部分Warrior,但从您的代码的其余部分来看,它看起来Warrior应该是第一个参数,item应该是第二个。这就是其他两种情况(带有 的情况Mage)的编写方式。


推荐阅读