Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 408
f23aaz Avatar asked Mar 03 '23 05:03

f23aaz


1 Answers

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
like image 108
Willem Van Onsem Avatar answered Mar 11 '23 12:03

Willem Van Onsem