Bercovici Adrian
Bercovici Adrian

Reputation: 9370

How to enforce type when using point free notation

Hello how can you enforce GHC type for functions such as Data.Text.read or the =~ operator from Text.Regex.Posix when composing methods?

example:
a=["1.22","3.33","5.55"]

Without point free:
b= map (\x-> read x ::Double) a

How to enforce a type for read with point free notation ?

b=map read::Double a or
b= map (read . f1 .f2 .f3... . fn )::Double a (when composing methods)
where f1 , f2 ...fn are methods

Or better how do you specify the read type when it belongs in a chain of methods ,BUT not at the end of the chain ! :
b=map (f2 . read . f1 ) a

Upvotes: 7

Views: 126

Answers (2)

chepner
chepner

Reputation: 532208

read has type String -> a, so read x has type a. Just like forcing read x to have type Double instead of a with read x :: Double, you can force read to have type String -> Double instead:

b = map (read :: String -> Double) a

Upvotes: 3

leftaroundabout
leftaroundabout

Reputation: 120751

The best way in modern Haskell is with a type application.

Prelude> :set -XTypeApplications 
Prelude> map (read @Double) ["1.22","3.33","5.55"]
[1.22,3.33,5.55]
Prelude> map (read @Int) ["1.22","3.33","5.55"]
[*** Exception: Prelude.read: no parse

This works because read has the signature

read :: ∀ a . Read a => String -> a

and therefore read @Double specialises a ~ Double and thus

read @Double :: String -> Double

Upvotes: 11

Related Questions