哈斯克尔:显示搞砸了? [英] Haskell: Show screwed up?

查看:128
本文介绍了哈斯克尔:显示搞砸了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显示在Haskell功能似乎并没有做什么它应该:

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>

当我宣布的功能,我通常把类型签名为显示中,不与换行正确处理。我想它来治疗 \\ n 为换行符,而不是从字面上\\ n。当我将类型更改为字符串的,功能正常工作。但是我必须实现一个单独的函数整数,浮点数,等等等等。

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?

推荐答案

在Haskell显示方法的合同是它产生一个字符串,评估时,会产生被显示的值。

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>

这篇关于哈斯克尔:显示搞砸了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆