Coercions
"I have a Float
but want a Double
". Or: I have a String
but want a Text
.
Answer¶
Usually one can find the right function via Hoogle:
However, a more convenient option is to use the Witch
library, which abstracts coercions using a single function, called into
:
{-# LANGUAGE TypeApplications #-} -- (1)!
import Witch -- (2)!
float :: Float
float = 4
double :: Double
double = into @Double float -- (3)!
str :: String
str = "hello"
text :: Text
text = into @Text str
-
Only needed if you aren't using GHC2021.
-
This is a library for performing coercions.
-
The use of the
@Double
here directs helps the type checker infer the output type ofinto
. Only needed if you don't supply the type signaturedouble :: Double
.
Last update:
January 12, 2023
Created: August 18, 2022
Created: August 18, 2022