我正在尝试编写一个带有String
和Int
的函数,并返回该字符串“int”次。那就是:
duplicate :: String -> Int -> String
如果我要写duplicate "Hello" 3
,则输出应为"HelloHelloHello"
。
答案 0 :(得分:17)
轻松:
duplicate :: String -> Int -> String
duplicate string n = concat $ replicate n string
$
是a function of type (a -> b) -> a -> b
。该语言允许使用非字母数字名称的函数以中缀形式(作为运算符)使用。即,上述函数的主体与以下表达式完全相同:
($) concat (replicate n string)
$
所做的只是让你摆脱大括号。这意味着上述表达式只是以下表达式的替代:
concat (replicate n string)
答案 1 :(得分:8)
String
只是Char
列表的同义词,列表类型为Monad
。因此
duplicate :: Int -> String -> String
duplicate n str = [1..n] >>= const str
或者,如果你想获得所有无点
duplicate = (. const) . (>>=) . enumFromTo 1
修改强>
正如评论中所建议的
duplicate n str = [1..n] >> str
或
duplicate = (>>) . enumFromTo 1
答案 2 :(得分:5)
您可以按如下方式使用replicate
和concat
:
duplicate :: [a] -> Int -> [a]
duplicate = flip $ (concat .) . replicate
-- or as larsmans suggested:
duplicate :: [a] -> Int -> [a]
duplicate = (concat .) . flip replicate
然后将其用作duplicate "Hello" 3
。
答案 3 :(得分:3)
您可以使用模式匹配。
duplicate _ 0 = []
duplicate xs n = xs ++ duplicate xs (n-1)
或
duplicate xs n | n==0 = []
| otherwise = xs ++ duplicate xs (n-1)
答案 4 :(得分:1)
初学者再次尝试使用递归
duplicate s n = if n <= 1 then s else duplicate (n-1) s ++ s
虽然如果n为负或为零,函数应该做什么有点不清楚。所以我选择返回字符串本身。