基本的haskell:复制元素 [英] basic haskell : Copying elements
问题描述
我试图递归地调用一个函数来复制任何类型的指定次数的
,例如复制3'a'会给我['a','a','a'],同时复制3 2会给我[2,2,2]
这是我到目前为止,但我不知道我的字体是否正确,因为我认为我的代码应该运行良好。任何人都可以看到有什么问题吗?
copy :: Int-> a-> [a]
copy x [] = []
copy ya = a:(copy(y-1)a)
编辑:更新为:
copy :: Int-> a-> [a]
copy 0 a = []
copy ya = [a] ++(copy(y-1)a)
然而,这给了我aaa而不是[a,a,a]
关于如何以更多的凯克利方式实现你的功能的建议。您正试图实现标准的复制
函数,并且查看标准源代码总是有所帮助。这里是复制的代码(简化后)
$ pre $复制nx =取n(重复x)
重复x = xs其中xs = x:xs
源代码取自haskell上由lambdabot返回的简化src irc。
I'm trying to recursively call a function that copies any type a specified amount of times for example copy 3 'a' would give me ['a','a','a'] while copy 3 2 would give me [2,2,2] This is what I have so far but I'm not sure if my typeline is correct as I think my code should run fine. Can anyone see what's wrong?
copy :: Int->a->[a]
copy x [] = []
copy y a = a:(copy (y-1) a)
edit: updated to this:
copy :: Int->a->[a]
copy 0 a = []
copy y a = [a]++(copy (y-1) a)
However this gives me "aaa" instead of [a,a,a]
This is just a suggestion about how to implement your function in a more haskelly way. You are trying to implement standard replicate
function and looking at the standard source code always help. Here is the code for replicate (after simplification)
replicate n x = take n (repeat x)
repeat x = xs where xs = x : xs
The source code is taken from the simplified src returned by lambdabot on haskell irc.
这篇关于基本的haskell:复制元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!