string - Haskell 中连接字符串和 IO 整数

标签 string haskell io integer concatenation

我编写了一个函数,将当前屏幕宽度返回为 IO Integer(到目前为止有效)。

getScreenWidth:: IO Integer
getScreenWidth = do
                    (sx, sy, w, h) <- getScreenDim 0
                    return $ sx

现在我想将屏幕宽度添加到字符串中:

> magic_function :: IO Integer -> String -> ... magic output type
> magic_function = ... ? this is where i am stack at ? ...

我想将魔术函数传递给一个字符串,例如“屏幕宽度:”,我希望它添加当前屏幕宽度,以便我得到“屏幕宽度:1680”。如何连接 IO 整数和普通字符串?它可以与show一起使用吗?

有人可以帮我吗?

最佳答案

首先,忘记 IO:

labelInteger :: String -> Integer -> String
labelInteger label number = label ++ ": " ++ show number

现在担心 IO:

import Control.Monad (liftM, liftM2)

labelIOInteger :: String -> IO Integer -> IO String
labelIOInteger label ioNumber = liftM (labelInteger label) ioNumber

用作例如labelIOInteger“屏幕宽度”getScreenWidth...但要小心!如果你这样做:

widthLabel <- labelIOInteger "Screen width" getScreenWidth
isPortrait <- liftM2 (<) getScreenWidth getScreenHeight

...然后 getScreenWidth 将被执行两次...诚然,对于这个特定的操作来说这不太可能是一个问题,但如果它是一个从文件或文件中读取整数的操作数据库或网站,您可以看到执行两次可能是不可取的。

通常最好不要编写像 labelIOInteger 这样的函数,而是这样做:

widthLabel <- liftM (labelInteger "Screen Width") getScreenWidth

...这样,如果您发现自己需要使用返回值进行两个不同的计算,您可以轻松重构:

screenWidth <- getScreenWidth
let widthLabel = labelInteger "Screen Width" screenWidth
isPortrait <- liftM (screenWidth <) getScreenHeight

关于string - Haskell 中连接字符串和 IO 整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16197285/

相关文章:

c - 如何从文件中获取替代行并将其作为字符串存储到结构中?

java - 从文件中读取 ArrayList 作为对象?

c - 文件 IO : Line by Line Comparison In C, 段错误

performance - 严格构造函数的部分应用

data-structures - 哪个基于树的字典在功能上最容易实现?

c# - C# 中的 I/O 级联

r - 在 R 中的多个字符串中选择可变长度字符串

c# - 为什么默认的字符串比较器无法保持传递一致性?

C++:使用 isdigit 检查字符串字符是否为数字。 .

haskell - 类型类实例内的类型类约束