Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 919
Bercovici Adrian Avatar asked Sep 11 '18 12:09

Bercovici Adrian


2 Answers

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
like image 137
leftaroundabout Avatar answered Oct 21 '22 14:10

leftaroundabout


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
like image 34
chepner Avatar answered Oct 21 '22 12:10

chepner