Haskell: Show screwed up?

前端 未结 6 512
小鲜肉
小鲜肉 2021-01-17 17:34

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

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


overfl         


        
6条回答
  •  遥遥无期
    2021-01-17 18:18

    Porges' plan works and I think it brings out brings out what show is really up to, since the confusing behavior you found in ghci will still turn up if you get the IO function you want. Note that I added an instance for Char to Porges' code, since you would presumably want that not to have quotes.

    {-# LANGUAGE UndecidableInstances, OverlappingInstances,
             FlexibleInstances, TypeSynonymInstances #-}
    class ToString a where
      toString :: a -> String
    
    instance ToString String where
      toString = id
    
    instance ToString Char where
      toString x = [x]
    
    instance Show a => ToString a where
      toString = show
    
    foo :: (ToString a) => a -> IO ()
    foo x = do {putStrLn $ toString x}
    

    then, in ghci, watch what happens with foo.show:

    *Main> let str =  "stack\n\noverflow"   
    *Main> show str   
    "\"stack\\n\\noverflow\""    
    *Main> putStrLn str   
    stack  
    
    overflow  
    *Main> putStrLn (show str)  
    "stack\n\noverflow"  
    *Main> foo str   
    stack  
    
    overflow  
    *Main> foo (show str)  
    "stack\n\noverflow"  
    *Main> foo ( show (show str))  
    "\"stack\\n\\noverflow\""  
    *Main> let newl = "\n"  
    *Main> foo newl  
    
    
    *Main> putStrLn newl  
    
    
    *Main> putStrLn (show newl)  
    "\n"   
    
    
    
    *Main> foo (show newl)  
    "\n"  
    *Main> foo (show (show newl))  
    "\"\\n\""  
    *Main> 
    

提交回复
热议问题