如何将变量转换为字符串?

发布于 2024-07-09 10:31:18 字数 42 浏览 10 评论 0原文

例如,这样它就可以像这样工作 toString(Var x)=“x”

For example so that it works like this
toString (Var x)= "x"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风柔一江水 2024-07-16 10:31:18

使用 show 函数:

putStrLn (show x)

将打印出“x”变量。 (当然,您不需要将它与 putStrLn 一起使用,或者 - show 返回一个可以像字符串一样在任何地方使用的字符串。)

Use the show function:

putStrLn (show x)

will print out the "x" variable. (Naturally, you don't need to use it with putStrLn, either -- show returns a string that can be used anywhere like a string.)

忱杏 2024-07-16 10:31:18

如果我理解正确的话,您是在问如何将编程结构转换为字符串。 您并不关心“x”代表什么,而是关心程序员在源文件中将其称为“x”。

您可以使用一些“废弃您的样板”组件将数据构造函数转换为字符串。 这是一个符合您要求的示例。

{-# LANGUAGE DeriveDataTypeable #-}

module Main where

import Data.Data

data Var a = Var a
data X = X deriving (Data, Typeable)

toString :: Data a => Var a -> String
toString (Var c) = show (toConstr c)

main :: IO ()
main = putStrLn $ "toString (Var x)= " ++ show (toString (Var X))

输出:

$ ghci Test.hs
GHCi, version 6.10.4: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling Main             ( Test.hs, interpreted )
Ok, modules loaded: Main.
*Main> main
toString (Var X)= "X"
*Main>

对于一个真实的例子,我建议查看 RJson 库

If I understand you correctly, you're asking how to convert programming constructs into strings. You aren't concerned with what 'x' represents so much as you are that the programmer called it "x" in the source file.

You can convert data constructors into strings using some of the Scrap Your Boilerplate components. Here's an example that does just what you asked.

{-# LANGUAGE DeriveDataTypeable #-}

module Main where

import Data.Data

data Var a = Var a
data X = X deriving (Data, Typeable)

toString :: Data a => Var a -> String
toString (Var c) = show (toConstr c)

main :: IO ()
main = putStrLn $ "toString (Var x)= " ++ show (toString (Var X))

output:

$ ghci Test.hs
GHCi, version 6.10.4: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling Main             ( Test.hs, interpreted )
Ok, modules loaded: Main.
*Main> main
toString (Var X)= "X"
*Main>

For a real example, I suggest looking at the RJson library.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文