basic haskell : Copying elements

岁酱吖の 提交于 2020-01-25 10:27:08

问题


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]


回答1:


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.



来源:https://stackoverflow.com/questions/19456756/basic-haskell-copying-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!