Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is is possible to refer to Type Variables in pattern matching?

The following code (which is not meant to do anything useful) compiles fine :

{-# LANGUAGE ScopedTypeVariables #-}
import System.Random

uselessFunction :: (RandomGen g) => g -> [Int]
uselessFunction gen = 
  let (value::Int, newGen) = (random gen)
  in (uselessFunction newGen)

Is it possible for me to use type variables in the pattern matching, in the following spirit (code fails to compile):

{-# LANGUAGE ScopedTypeVariables #-}
import System.Random

uselessFunction :: (RandomGen g, Random a) => g -> [a]
uselessFunction gen = 
  let (value::a, newGen) = (random gen)
  in (uselessFunction newGen)
like image 416
artella Avatar asked Feb 14 '23 14:02

artella


1 Answers

You've already noticed that the ScopedTypeVariables extension allows you to put type annotations on patterns. But for the extension's main purpose, to make a type variable be locally scoped so that you can refer to it inside the function, you must also declare it with a forall in the type declaration, like so:

uselessFunction :: forall a g. (RandomGen g, Random a) => g -> [a]

This doesn't change the meaning of the declaration itself, but hints to GHC that you may want to use the variable locally.

like image 53
Ørjan Johansen Avatar answered Mar 08 '23 08:03

Ørjan Johansen