Search code examples
haskellimplicit

Implicitly call function


I need to find a way to implicitly call a function in Haskell in a similar way that you can do using implicit functions in Scala.

I've looked into using {-# LANGUAGE ImplicitParams #-} like shown in Implicit parameter and function but I can't figure out how to achieve something similar without explicitly defining it.

This is a very reduced version of my code

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

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

I want to be able to run

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

as well as

Test> a 5 -- outputs 6

Solution

  • What you here describe is ad hoc polymorphism [wiki]. In Haskell that is achieved through type classes [wiki].

    We can for example define a class:

    class Foo c where
        a :: c -> Int

    Now we can define two instances of Foo: an instance for Int, and an instance for String:

    {-# LANGUAGE FlexibleInstances #-}
    
    instance Foo [Char] where
        a = length
    
    instance Foo Int where
        a = (+) 1

    Next we thus can call a with:

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