Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Haskell how can you multiply a string?

Tags:

haskell

I'm trying to write a function that takes a String and an Int and returns that string "int" times. That is:

duplicate :: String -> Int -> String

If I were to write duplicate "Hello" 3 the output should be "HelloHelloHello".

like image 556
benharris Avatar asked Nov 27 '13 15:11

benharris


People also ask

How do you multiply a string?

To (properly) multiply an string by an integer, you split the string into characters, repeat each character a number of times equal to the integer, and then stick the characters back together. If the integer is negative, we use its absolute value in the first step, and then reverse the string.

Can we multiply a string?

Multiplication. You can do some funny things with multiplication and strings. When you multiply a string by an integer, Python returns a new string. This new string is the original string, repeated X number of times (where X is the value of the integer).

How do you multiply float and Int in Haskell?

In Haskell you can't multiply an Int by a Float because the * operator has type Num a => a -> a -> a - it takes two values of the same numeric type and gives you a result that is that type. You can multiply an Int by an Int to get an Int , or a Float by a Float to get a Float .

What is a string in Haskell?

Haskell string is a data type which is used to store the value of variable in the form of string, string is represented by the sequence of character in Haskell or in any other programming language as well.


3 Answers

Easily:

duplicate :: String -> Int -> String
duplicate string n = concat $ replicate n string

The $ is a function of type (a -> b) -> a -> b. The language allows the functions with non-alpha-numeric names to be used in infix form (as operators). I.e., the body of the function above is absolutely identical to the following expression:

($) concat (replicate n string)

What $ does is just allows you to get rid of braces. Meaning that the above expressions are just an alternative to the following expression:

concat (replicate n string)
like image 69
Nikita Volkov Avatar answered Sep 24 '22 14:09

Nikita Volkov


A String is just a synonym for a list of Char, and the list type is a Monad. Therefore

duplicate :: Int -> String -> String
duplicate n str = [1..n] >>= const str

Or, if you wanted to get all point-free

duplicate = (. const) . (>>=) . enumFromTo 1

Edit

As suggested in the comments

duplicate n str = [1..n] >> str

or

duplicate = (>>) . enumFromTo 1
like image 30
Chris Taylor Avatar answered Sep 23 '22 14:09

Chris Taylor


You can use replicate and concat as follows:

duplicate :: [a] -> Int -> [a]
duplicate = flip $ (concat .) . replicate

-- or as larsmans suggested:

duplicate :: [a] -> Int -> [a]
duplicate = (concat .) . flip replicate

Then use it as duplicate "Hello" 3.

like image 30
Aadit M Shah Avatar answered Sep 22 '22 14:09

Aadit M Shah