Where's function type in Haskell

For example, I have the following function:

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

and I need to specify literals like 0.5 - 't'

If I write smth. for example, (0.5::t) , GHC creates a new variable of type 't0' that does not match the original 't'.

I wrote a little function

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

and use it as follows:

 b = bar (ct var 0.5) d 

Is there a better solution?

+4
source share
2 answers

You can use ScopedTypeVariables to transfer type variables from a top-level signature to 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 the arguments turned upside down - already in Prelude,

 ct = flip asTypeOf 

So

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

will work too.

+8
source

Without ScopedTypeVariables, the usual solution is to rewrite b into a function such that it takes type t and returns something containing type t . Thus, its t is general and independent of external t and can be inferred based on where it is used.

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

+1
source

Source: https://habr.com/ru/post/1397325/


All Articles