1

So I've got two functions that based on their types, I feel like I should be able to combine with function composition.

ghci> :t show  
show :: Show a => a -> String  
ghci> :t putStrLn  
putStrLn :: String -> IO ()  

An initial attempt was successful,

ghci> ( putStrLn . show ) "Hello World!"  
"Hello World!"  

I figured I'd try defining a new function as that composition

ghci> let myShow = putStrLn . show  

But it didn't work:

ghci> myShow "Hello World!"  

<interactive>:28:8:  
    Couldn't match expected type `()' with actual type `[Char]'  
    In the first argument of `myShow', namely `"Hello World!"'  
    In the expression: myShow "Hello World!"  
    In an equation for `it': it = myShow "Hello World!"  

Interestingly, the type of my myShow function became () -> IO ()

ghci> :t myShow   
myShow :: () -> IO ()  

I had assumed that the type would have been Show a => a -> IO () .

Does anyone know why this attempt at function composition failed?

(I realize that this is probably a pretty basic question, but I'm just getting started with the language, so bear with me here)

martin
  • 1,102
  • 2
  • 12
  • 20
  • 2
    You've done nothing wrong as a beginner. The dreaded [monomorphism restriction](https://wiki.haskell.org/Monomorphism_restriction) didn't like the type variable `a` (that you inferred correctly) and filled in the unit type. – Bergi May 15 '17 at 03:11
  • Also a beginner in Haskell, why did it work for me? In GHCi `:t myShow` returned `myShow :: Show a => a -> IO ()` – Henry May 15 '17 at 03:15
  • Ah, believe it was because I had previously done `:set -XNoMonomorphismRestriction`. Although, I would have thought that would reset when I quit GHCi. – Henry May 15 '17 at 03:19
  • @Bergi thanks for the link – martin May 15 '17 at 03:20
  • 3
    @name It might be due you and martin using different versions of GHC -- the monomorphism restriction is turned off by default in GHCi (but not elsewhere) since GHC 7.8.1. – duplode May 15 '17 at 03:24
  • @duplode Thanks! On version 8.0.1, so that must be it. – Henry May 15 '17 at 03:27
  • 2
    By the way `putStrLn . show` is what `print` does. – 4castle May 15 '17 at 03:38

0 Answers0