Haskell: `show` option that does not wrap String and Char in quotation marks

I need an option show(let it be called label) that acts like show, except that it does not end Stringin " "or Charin ' '. Examples:

> label 5
"5"
> label "hello"
"hello"
> label 'c'
"c"

I tried to do this manually, but I ran into some walls. Here is what I tried:

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
module Label where

class (Show a) => Label a where
    label :: a -> String

instance Label [Char] where
    label str = str

instance Label Char where
    label c = [c]

-- Default case
instance Show a => Label a where
    label x = show x

However, since the case class overrides instance Label [Char]and by default instance Label Char, these types do not work with the function label.

Is there a library function that provides this function? If not, is there a way around the above code?

+3
source share
4 answers

, "head" , . "", =>, " a", . , . - .

, , , , , Label. ? , , - .

, , OverlappingInstances, . OverlappingInstances GHC , " " . , , .

TypeSynonymInstances, , :

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Label where

class (Show a) => Label a where
    label :: a -> String

instance Label String where label x = x

instance Label Char where label x = [x]

instance (Show a) => Label a where label = show
+4

OverlappingInstances, .

+1

, ?

. , , toS, show. (. )

cabal string-conv : cabal install string-conv

: Hackage

+1

, , (Typeable) :

Data.Generics > (show `extQ` (id:: String β†’ String)` extQ` ((: []):: Char β†’ String)) 1

"1"

Data.Generics > (show `extQ` (id:: String β†’ String)` extQ` ((: []):: Char β†’ String)) "hello"

""

Data.Generics > ( `extQ` (id:: String β†’ String)` extQ` ((: []):: Char β†’ String)) 'c'

""

Data.Generics > ( `extQ` (id:: String β†’ String)` extQ` ((: []):: Char β†’ String)) ['f', 'l']

""

Data.Generics > : t ( `extQ` (id:: String β†’ String)` extQ` ((: []):: Char β†’ String))

( `extQ` (id:: String β†’ String)` extQ` ((: []):: Char β†’ String)):: ( a, Typeable a) = > a β†’ String

0
source

Source: https://habr.com/ru/post/1748453/


All Articles