解决重载函数的歧义
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)
我想在 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)