如何在Haskell中将Integers连接为字符串?

Mah*_*lut 3 string haskell integer concatenation

我想在Haskell中连接字符串,也可以在函数中连接整数,如下所示:

arc 13 34 234 3
Run Code Online (Sandbox Code Playgroud)

13 34 234 3将是arc函数的参数,我希望输出像

"arc(13, 34, 234, 3)"
Run Code Online (Sandbox Code Playgroud)

作为String我该如何实现呢?

ДМИ*_*КОВ 7

如何将数字列表连接成一个字符串?看起来某些[Int] -> String功能可以帮到这里.

> concat . intersperse ", " . map show $ [13, 34, 234, 3]
"13, 34, 234, 3"
Run Code Online (Sandbox Code Playgroud)

所以,让我们为该String添加一些括号和"arc".

import Data.List (intersperse)

arc :: [Int] -> String
arc nums = "arc(" ++ (concat . intersperse ", " . map show $ nums) ++ ")"
Run Code Online (Sandbox Code Playgroud)

我们得到了答案.

> arc  [13, 34, 234, 3]
"arc(13, 34, 234, 3)"
Run Code Online (Sandbox Code Playgroud)

如果你真的需要具有签名功能Int -> Int -> Int -> Int -> String:

arc' :: Int -> Int -> Int -> Int -> String
arc' a1 a2 a3 a4 = "arc(" ++ (concat . intersperse ", " . map show $ [a1,a2,a3,a4]) ++ ")"

> arc' 13 34 234 3
"arc(13, 34, 234, 3)"
Run Code Online (Sandbox Code Playgroud)


Die*_*Epp 5

如果你想要String输出,典型的技术是创建一个ShowS,这只是另一个名称String -> String.

showsArc :: Int -> Int -> Int -> Int -> ShowS
showsArc a b c d = showString "arc" . shows (a, b, c, d)

>>> showsArc 13 34 234 3 []
"arc(13,34,234,3)"
Run Code Online (Sandbox Code Playgroud)

[]在函数调用结束只是一个空字符串.它允许您将数据附加到末尾,而不必担心O(N)字符串连接.

>>> showsArc 13 34 234 3 " and some extra text"
"arc(13,34,234,3) and some extra text"
Run Code Online (Sandbox Code Playgroud)

  • 您不能命名以大写字母开头的函数(或值):`Arc`是Haskell中的无效函数名.(只有以大写字母开头的构造函数,类型,模块和类命名.) (5认同)