Tor*_*nny 2 parameters polymorphism haskell typeclass
我怎么能写一个像int gog(float i)和float gog(int i)(通常称为"重载")的函数?一些简单的重载可以通过实现
class PP a where
gog :: a -> Int
instance PP Bool where
gog _ = 1
instance PP Char where
gog _ = 1
Run Code Online (Sandbox Code Playgroud)
但上面的例子只使参数具有多态性.如果我们想要使参数和结果都具有多态性,我们必须编写如下内容:
class PP a where
gog :: Uu b => a -> b
class UU a where
-- This function can convert between different types of UU.
fromUuToUu :: UU b => a -> b
Run Code Online (Sandbox Code Playgroud)
没有fromUuToUu,结果中的多态性gog是不可能的.但我不能写fromUuToUu,这与这个问题的主题相关,即如何创建一个参数和结果都是多态的函数.
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-}
class Poly a b where
gog :: a -> b
instance Poly Int String where
gog = show
instance Poly String Int where
gog = read
instance Poly Int Float where
gog = fromIntegral
instance Poly Float Float where
gog = (*) 2
Run Code Online (Sandbox Code Playgroud)
gog 现在是"完整的"多态的.