简体   繁体   English

带字符的 Haskell 递归

[英]Haskell Recursion with Chars

Write a recursive Haskell function编写递归 Haskell 函数

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

such that makeString n ch1 ch2 returns a string as follows:使得makeString n ch1 ch2返回一个字符串,如下所示:

  • When n is positive, the string has length 3n-2 and contains n copies of ch1, each copy separated by two copies of ch2.当 n 为正数时,字符串长度为 3n-2 并包含 ch1 的 n 个副本,每个副本由 ch2 的两个副本分隔。
  • When n is less than or equal to zero, the string is the empty string.当 n 小于或等于 0 时,该字符串为空字符串。

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. replicate创建足够长的列表供merge完成其工作。 Works for all positive n s适用于所有正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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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