我如何在Haskell中编写如下内容:
showSquare :: (Show a, Num a) => a -> String
showSquare x = "The square of " ++ (show x) ++ " is " ++ (show (x * x))
showSquare :: (Show a, not Num a) => a -> String
showSquare x = "I don't know how to square " ++ (show x)
Run Code Online (Sandbox Code Playgroud)
基本上,类似于C++中的boost :: enable_if.
GHC扩展是可以的.
你为什么要这个?该typechecker可以确保你将永远不会叫showSquare上一些东西,是不是Num在第一种情况.在Haskell中没有instanceof,因为所有内容都是静态输入的.
它不适用于任意类型:您只能定义自己的类型类,例如
class Mine a where
foo :: a -> String
instance (Num a) => Mine a where
foo x = show x*x
Run Code Online (Sandbox Code Playgroud)
并且您可以为其他类添加更多实例,但是您将无法仅为instance Mine a任意类编写a.另外一个instance (Show a) => ...也没有帮助,因为也不允许重叠实例(链接描述了解决它的方法,但它需要相当多的额外机制).