Haskell:表演搞砸了? [英] Haskell: Show screwed up?

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

问题描述

Haskell 中的 show 函数似乎没有做它应该做的:

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>

当我声明函数时,我通常将类型签名设为Show,这不会正确处理换行符.我希望它将 \n 视为换行符,而不是字面上的 "\n".当我将类型更改为 String 时,函数工作正常.但我必须为整数、浮点数等实现一个单独的函数.

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

...并这样称呼它:

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

我如何让函数返回预期的内容?IE.哪个函数类似于 show 但可以返回包含换行符的字符串?

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 中 show 方法的契约是它产生一个字符串,当评估时,产生显示的值.

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> 

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

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