#{[1,2,3].length}" 以下尝试是 -6ren">
gpt4 book ai didi

Haskell中的字符串插值

转载 作者:行者123 更新时间:2023-12-03 12:00:17 25 4
gpt4 key购买 nike

我想编写将输出的代码:

length [1,2,3] => 3   

在 Ruby 中,我可以这样做:
puts "length [1,2,3] => #{[1,2,3].length}"

以下尝试是 Haskell 失败...
Prelude Data.List> print "length [1,2,3]"
"length [1,2,3]"
Prelude Data.List> print (length [1,2,3])
3
Prelude Data.List> print "length [1,2,3]" (length [1,2,3])

<interactive>:1:0:
Couldn't match expected type `Int -> t'
against inferred type `IO ()'
In the expression: print "length [1,2,3]" (length [1, 2, 3])
In the definition of `it':
it = print "length [1,2,3]" (length [1, 2, 3])
Prelude Data.List>

最佳答案

您也可以使用 Text.Printf 它包含在 GHC 基础库中:

> let format s = printf "length %s => %d\n" (show s) (length s)
> format [1,2,3]
length [1,2,3] => 3

Hackage 上有几个字符串插值包 http://hackage.haskell.org如果你想要更好的情况。

关于Haskell中的字符串插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1264797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com