4

For example, i've got following function:

foo :: t -> f
foo var = foo' b var
    where
        b = bar 0.5 vect

and I need to specify literals' 0.5 type — 't'

If i write smth. like (0.5::t), GHC creates new type variable 't0', which is not corresponding to original 't'.

I've wrote a small function

ct :: v -> v -> v
ct _ u = u

and use it like this:

b = bar (ct var 0.5) d

Is there any better solution?

3
  • There's a compiler option that will let you say (0.5::t) and it will match the t to the surrounding scope's t, but I forget what it is. Commented Feb 19, 2012 at 21:41
  • 1
    you wrote very little information - for example what is bar respectively bar's type signature and foo' as well. as i understand it lowercase letters are placeholders for ghc to be inferred. known types start with an uppercase letter like Float or Int so you pass almost no type information to the compiler which is asking for more information. Commented Feb 19, 2012 at 21:48
  • if you try to load the file with ghci the interpreter does it still fail - as i remember it is less strictly. in addition you can find out about a function's type by :t foo Commented Feb 19, 2012 at 21:52

2 Answers 2

8

You can use ScopedTypeVariables to bring the type variables from the top-level signature into scope,

{-# LANGUAGE ScopedTypeVariables #-}

foo :: forall t. Fractional t => t -> f
foo var = foo' b var
  where
    b = bar (0.5 :: t) vect

Your helper function ct is - with flipped arguments - already in the Prelude,

ct = flip asTypeOf

so

  where
    b = bar (0.5 `asTypeOf` var) vect

would work too.

Sign up to request clarification or add additional context in comments.

Comments

1

Without ScopedTypeVariables, the usual solution is to re-write b into a function such that it takes in type t and returns something containing type t. That way, its t is generic and independent of the outer t and can be inferred based on where it is used.

However, without knowing the types of your foo' and bar, etc., I cannot tell you what exactly it will look like

Comments

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.