Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Where' function type in Haskell

Tags:

types

haskell

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?

like image 509
Paul Hooks Avatar asked Jan 18 '23 10:01

Paul Hooks


1 Answers

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.

like image 109
Daniel Fischer Avatar answered Jan 25 '23 07:01

Daniel Fischer