Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Show screwed up?

Tags:

haskell

api

The show function in Haskell doesn't seem to do what it should:

Prelude> let str = "stack\n\noverflow"
Prelude> putStrLn str
stack


overflow
Prelude> show str
"\"Stack\\n\\n\\noverflow\""
Prelude>

When I declare functions, I normally put the type signatures as Show, which doesn't deal with newlines correctly. I want it to treat \n as newlines, not literally "\n". When I change the type to String, the functions work fine. But I'd have to implement a seperate function for integers, floats, etc, etc.

For example, I may declare a function:

foo :: (Show x) => x -> IO ()
foo x = do
  putStrLn $ show x

... and call it this way:

foo "stack\n\noverflow"
foo 6
foo [1..]

How would I get the function to return what's expected? I.e. which function is similar to show but can return strings containing newlines?

like image 967
Lucky Avatar asked Jun 09 '09 04:06

Lucky


3 Answers

The contract of the show method in Haskell is that it produce a string that, when evaluated, yields the value that was shown.

Prelude> let str = "stack\n\noverflow"
Prelude> putStrLn str
stack

overflow
Prelude> putStrLn (show str)
"stack\n\noverflow"
Prelude> 
like image 189
Dave Avatar answered Oct 06 '22 00:10

Dave


Sounds like you're trying to simulate a ToString method, although some of your terminology is a little confusing.

You can simulate it like this:

{-# LANGUAGE UndecidableInstances, OverlappingInstances,
             FlexibleInstances, TypeSynonymInstances #-}

class ToString a where
    toString :: a -> String

instance ToString String where
    toString = id

instance Show a => ToString a where
    toString = show

However, as shown by the LANGUAGE pragmas, this is not very desirable. To really get a feel for what you're trying to do it would be easier if we had more context...

like image 37
porges Avatar answered Oct 05 '22 22:10

porges


show shows the variable in the way that you entered it.

Seems pretty regular to me.

like image 31
Alex Gartrell Avatar answered Oct 05 '22 23:10

Alex Gartrell