隐式调用函数

Implicitly call function

我需要找到一种方法来隐式调用 Haskell 中的函数,其方式与您在 Scala 中使用 implicit 函数的方式类似。

我研究过使用 {-# LANGUAGE ImplicitParams #-},如 Implicit parameter and function 中所示,但我不知道如何在不明确定义的情况下实现类似的功能。

这是我的代码的简化版本

a :: Int -> Int
a n = n + 1

b :: [Char] -> Int
b cs = length cs

我希望能够运行

Test> a "how long" -- outputs 8, as it implicitly calls a (b "how long")

以及

Test> a 5 -- outputs 6

你这里描述的是ad hoc polymorphism [wiki]. In Haskell that is achieved through type classes [wiki]

我们可以定义一个 class:

class Foo c where
    a :: c -> Int

现在我们可以定义 Foo 的两个实例:Int 的实例和 String 的实例:

{-# LANGUAGE <b>FlexibleInstances</b> #-}

instance Foo [Char] where
    a = length

instance Foo Int where
    a = (+) 1

接下来我们可以这样调用a

Prelude> a "how long"
8
Prelude> a (5 :: Int)
6