Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is going on when I compose "show" and "read" in Haskell?

Here's a short transcript from GHCi:

Prelude> :t read
read :: Read a => String -> a
Prelude> :t show
show :: Show a => a -> String
Prelude> :t show.read
show.read :: String -> String
Prelude> (show.read) "whales"
"*** Exception: Prelude.read: no parse

When I compose show and read I can only assume that GHC chose some arbitrary type which is both Readable and Showable to be the "intermediate" type.

How did it choose this type, and is there any way for me to find out what it is?

like image 900
Calvin Avatar asked Dec 09 '22 21:12

Calvin


1 Answers

The GHCi defaulting rules say that the chosen type is (). which is the default type that is chosen if a Show instance is demanded. GHCi will choose () for general constraints, Integer for numeric or integral constraints, and Double for fractional/other real constraints. This isn't due to some Haskell intrinsic; it's just how GHCi was implemented so that it can be used easily as a calculator.

If you had actually entered the code in a file and compiled it, the more strict GHC rules would have applied, and you would have gotten an error saying that the intermediate type cannot be resolved.

You can of course instruct GHC to use a different type by giving one of the functions a type, e.g.:

show . (read :: String -> Int)
like image 198
dflemstr Avatar answered Jan 28 '23 18:01

dflemstr