6

I want to concatenate strings in Haskell and also integers from function like this:

arc 13 34 234 3

13 34 234 3 will be arguments of arc function and I want output like

"arc(13, 34, 234, 3)"

as a String how can I implement this?

1
  • 1
    Are you sure that your arc function should have 4 Int arguments? Maybe [Int] will be more usable? Commented Mar 5, 2012 at 17:20

2 Answers 2

9

How can list of numbers could be concatenated into a string? Looks like some [Int] -> String function can help here.

> concat . intersperse ", " . map show $ [13, 34, 234, 3]
"13, 34, 234, 3"

So, let's add some brackets and "arc" to that String.

import Data.List (intersperse)

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

And we get the answer.

> arc  [13, 34, 234, 3]
"arc(13, 34, 234, 3)"

If you are really need function with signature like 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)"
Sign up to request clarification or add additional context in comments.

Comments

6

If you want String output, the typical technique is to create a ShowS, which is just another name for 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)"

The [] at the end of the function call is just an empty string. It lets you attach data to the end without worrying about O(N) string concatenation.

>>> showsArc 13 34 234 3 " and some extra text"
"arc(13,34,234,3) and some extra text"

2 Comments

i tried this but ghci gives ˙Arc.hs:30:1: Invalid type signature: Arc :: Int -> Int -> Int -> Int -> ShowS Should be of form <variable> :: <type> ˙
You can't name a function (or value) starting with a capital letter: Arc is an invalid function name in Haskell. (Only constructors, types, modules, and classes are named starting with capital letters.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.