Haskell:表演搞砸了?

编程入门 行业动态 更新时间:2024-10-25 23:34:03
本文介绍了Haskell:表演搞砸了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-18 13:31:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/938604.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:砸了   Haskell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!