[英]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.