3

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
f23aaz
  • 339
  • 2
  • 13
  • I'm not a haskeller but it seems that you're looking for single dispatching, dispatching based on argument type? You can create an instance of a for strings – geckos Nov 02 '19 at 18:01
  • 3
    You can do that by defining a typeclass, and then create instances for `String` and `Int`. – Willem Van Onsem Nov 02 '19 at 18:06

1 Answers1

7

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
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Is there any way of extending this so you can ignore the functions and convert automatically, such as `value :: Int \n value = "how long"` and it will call length without explicitly writing it? – f23aaz Nov 02 '19 at 20:39
  • 3
    @w1220 No, not generally. There is something for `String`, specifically (the `OverloadedStrings` extension), but I strongly recommend that you do not use it for this. Learn to write Haskell, not Scala, in your Haskell code. – Daniel Wagner Nov 03 '19 at 00:46