简体   繁体   中英

Haskell Recursion with Chars

Write a recursive Haskell function

makeString :: Int -> Char -> Char -> String

such that makeString n ch1 ch2 returns a string as follows:

  • When n is positive, the string has length 3n-2 and contains n copies of ch1, each copy separated by two copies of ch2.
  • When n is less than or equal to zero, the string is the empty string.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM