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"
.
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.
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).
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 .
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.
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)
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With