Haskell中的重载(显示和编号)

时间:2018-12-03 12:40:57

标签: haskell overloading

我正在Haskell中学习“重载”,尝试重载show和num clase时遇到一些问题。我使用新的递归数据,并且具有以下功能:

2018-12-03 10:11:19.104  WARN 11356 --- [io-8081-exec-10] c.g.e.controller.InformesController      : Context: org.springframework.security.core.context.SecurityContextImpl@ffffffff: Null authentication

功能正常运行,但是当我尝试创建2个实例时:

    module Nat where
data Nat = Zero | Suc Nat
--Zero = 0
--Suc (Suc zero) = 1
--suc (suc(suc zero)) = 2 
--nat2int:: Nat -> Int

nat2int Zero = 0
nat2int (Suc x) = 1 Prelude.+ nat2int x

--suma: Nat -> Nat -> Nat
suma Zero b = b --addition
suma (Suc a) b = Suc (suma a b)

--producto: Nat -> Nat -> Nat
producto Zero _ = Zero --product
producto (Suc m) n = suma n (producto m n)

我收到了这2条警告,如果您尝试使用show,sumar o producto,ghci编译器会给我一个错误:

module Sobrecarga where 
import Nat
instance Show Nat where
show Zero = "0"
show (Suc x) = Prelude.show (nat2int (Suc x))
instance Num Nat where
(+) a b = suma a b
(*) a b = producto a b

您是否有解决歧义的解决方案?

1 个答案:

答案 0 :(得分:2)

Those warnings are primarily a result of bad indentation in the definition of your instances. Instead of,

instance Show Nat where
show Zero = "0"
show (Suc x) = Prelude.show (nat2int (Suc x))

you should write,

instance Show Nat where
  show Zero = "0"
  show (Suc x) = Prelude.show (nat2int (Suc x))

and similarly for your Num instance. Then your Num instance is also missing quite a few methods,

instance Num Nat where
 (+) a b = suma a b
 (*) a b = producto a b

 abs         = ?    
 signum      = ?
 fromInteger = ?
 negate      = ?

You need to implement all those. Some further observations.

--Suc (Suc zero) = 1
--suc (suc(suc zero)) = 2 

I know this is commented out, but keep in mind Haskell is case-sensitive. So Suc and Zero must be capitalised.

nat2int Zero = 0
nat2int (Suc x) = 1 Prelude.+ nat2int x

It's a good idea to write down your type signature, furthermore you do not need that Prelude..

show Zero = "0"
show (Suc x) = Prelude.show (nat2int (Suc x))

Same here, get rid of Prelude., also there's no point in considering the case for zero and non-zero. It's enough to do,

show nat = show (nat2int nat)

or alternatively using composition,

show = show . nat2int
相关问题