Write a recursive Haskell function
makeString :: Int -> Char -> Char -> String
such that makeString n ch1 ch2
returns a string as follows:
For example, the function has the following behavior:
Main > makeString 5 'a' '!'
"a!!a!!a!!a!!a"
Main > makeString 1 'a' '!'
"a"
Main > makeString 10 '6' '#'
"6##6##6##6##6##6##6##6##6##6"
So far I have:
makeString :: Int -> Char -> Char -> String
makeString n ch1 ch2
|n <= 0 = [ ]
|otherwise = ch1: makeString(3*n-2)(ch2)(ch1)
Main> makeString 5 'a' '!'
"a!a!a!a!a!a!a!a!a!a!a!a!a!a!a!a!a!a!a!a"
A quick and dirty implementation
module Test where
merge :: [a] -> [a] -> [a]
merge xs [] = xs
merge [] ys = ys
merge (x:xs) (y:ys) = x : y : y : merge xs ys
makeString :: Int -> Char -> Char -> String
makeString 0 _ _ = []
makeString n ch1 ch2 = take ((3 * n) - 2) $ merge (replicate (3 * n) ch1) (replicate (3 * n) ch2)
The replicate
creates long enough lists for merge
to do its work. Works for all positive n
s
Here is my solution:
makeString :: Int -> Char -> Char -> String
makeString n ch1 ch2
| n <= 0 = ""
| n == 1 = [ch1]
| otherwise = [ch1, ch2, ch2] ++ makeString (n-1) ch1 ch2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.