[英]Resolving ambiguities for overloaded functions
我想在Haskell中有一个重载函数。
{-# LANGUAGE FlexibleInstances #-}
class Foo a where
foo :: a
instance Foo (String -> Int) where
foo = length
instance Foo String where
foo = "world"
然而,这种重载与类型模糊性的处理非常差。 print $ foo "hello"
会导致错误,而print $ length "hello"
工作正常。 但是,如果我的实例列表是固定的,那么为什么Haskell无法意识到foo :: String -> a
的唯一实例是foo :: String -> Int
,应该没有技术上的原因。 我可以让Haskell实现这个目标吗?
在这种特殊情况下很容易做到。 只是:
instance a ~ Int => Foo (String -> a) where foo = length
在你的情况下GHCI知道,那个foo :: String -> ??
我们要将签名更改为String -> Int
:
print (foo "hello" :: Int)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.