0

Assume, you have a class:

class AClass a where
  func:: Int

instance AClass SomeTree where
  func = 0

instance AClass Double where
  func = 1

How do I call the function func?

17
  • 1
    neutral :: Int, should work, since information both is gathered from the input type and output type. Commented Jan 8, 2021 at 14:03
  • 4
    There's no such thing as a function that takes no arguments. func here is just an Int. Use it like any other Int. The bigger issue is that you can't define func to have a type that doesn't involve a in some way. Commented Jan 8, 2021 at 14:13
  • 3
    @TVSuchty: Then you can use TypeApplications: func @Double. Commented Jan 8, 2021 at 14:18
  • 1
    You can add {-# LANGUAGE TypeApplications #-} to your file, which enables a new @ notation for providing type arguments. Then, you can write func @SomeTree, which will yield 0, or func @Double, which will yield 1. See the docs Commented Jan 8, 2021 at 14:23
  • 1
    Can you provide a more detailed example of what you are trying to do? Commented Jan 8, 2021 at 14:27

1 Answer 1

7
{-# LANGUAGE AllowAmbiguousTypes, TypeApplications #-}

class AClass a where
  func :: Int

instance AClass SomeTree where
  func = 0

instance AClass Double where
  func = 1

foo :: Int
foo = func @SomeTree + func @Double

{-# LANGUAGE ScopedTypeVariables, UnicodeSyntax #-}

bar :: ∀ a . AClass a => a -> Int
bar _ = func @a
Sign up to request clarification or add additional context in comments.

2 Comments

What magic does the bar Type constraint do? Thanks for the answer!
∀ a . is just what you implicitly have in functions like sum :: Num a => [a] -> a, which is actually shorthand for sum :: ∀ a . Num a => [a] -> a. The difference is that the explicit (aka forall) brings the a into scope in such a way that it can be used in the function body, as here with func @a.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.