2012-08-24 5 views
11

을 표시 할 때 code 다음 문자열 주위에 따옴표를 억제 :하스켈 :

data HelloWorld = HelloWorld; 
instance Show HelloWorld where show _ = "hello world"; 

hello_world = "hello world" 

main = putStr $ show $ (HelloWorld, hello_world) 

인쇄 :

(hello world,"hello world") 

내가 인쇄에 싶습니다

(hello world,hello world) 

즉 내가 동작을 원하지 다음과 같이 입력하십시오 :

제가 위에서 설명한 f처럼 작동하는 기능이 있는가

show "hello world" = "\"hello world\"" 

:

불행하게도, show는,이 만족하지 않는 이유는 무엇입니까?

+3

번역을 위해 새로운 typeclass (예 : 'PPrint')를 만드는 것이 좋습니다. 인간이 읽을 수있는'String'으로 변환합니다. –

+0

@Clinton이 답변을 도움이 되었습니까? –

답변

1

내가 당신을 위해이 작업을 수행하는 표준 typeclass이 믿지 않는,하지만 한 가지 해결 방법은 newtype은 정의하는 것입니다 : 다음

newtype PlainString = PlainString String 
instance Show PlainString where 
    show (PlainString s) = s 

show (PlainString "hello world") == "hello world"을하고 다른 유형 정상적으로 show을 사용할 수 있습니다 .

13

먼저 this question을 살펴보십시오. 어쩌면 당신은 toString 기능에 만족할 것입니다.

둘째, show은 어떤 값을 String에 매핑하는 함수입니다.

그래서, 그것은 인용 감각을 탈출해야합니다 : 제가 위에서 설명한 f처럼 작동하는 기능

> show "string" 
"\"string\"" 

있습니까? 당신이 id을 찾고있는 것처럼

이 보인다 다음이 될 것

{-# LANGUAGE TypeSynonymInstances #-} 

class PrintString a where 
    printString :: a -> String 

instance PrintString String where 
    printString = id 

instance PrintString HelloWorld where 
    printString = show 

instance (PrintString a, PrintString b) => PrintString (a,b) where 
    printString (a,b) = "(" ++ printString a ++ "," ++ printString b ++ ")" 

및 설명 F 기능 :

> putStrLn $ id "string" 
string 
> putStrLn $ show "string" 
"string" 
3

이 최종 해답을 완료하려면 다음 클래스를 정의 할 수 있습니다 printString 함수