开发者

help whats wrong with my code [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

replicate function help

decode [] = ""

decode = concatMap decodeHelper

    开发者_如何学Gowhere

      decodeHelper (1 x)  = [x]
      decodeHelper ( n x) = replicate n x

What is wrong with what I have done???

I have got a list [(Char,Int)] and I need to replicate the char by whatever the number is and I need to put it into a string so [(Char,Int)] -> String

for example

decode ['a',9'] will return "aaaaaaaaa"


You have a few syntax issues in the code. For one, tuples are written with a comma, so the patterns in decodeHelper should look like (n,x), not (n x). The latter will be interpreted by the compiler as calling a function n, passing x as the argument, which is certainly not what you meant.

It turns out that you don't need a special case for n equal to 1. Just using replicate 1 x will give you [x], just as you want. It also turns out that your special case for the empty list is unnecessary, since concatMap f applied to an empty list will yield the empty list, too. So removing these unnecessary cases and cleaning up your code, you get

decode = concatMap decodeHelper
  where decodeHelper (n, x) = replicate n x

One more (slightly more advanced) change would be to use uncurry rather than writing decodeHelper explicitly in a where clause, yielding the very simple and easy to read:

decode = concatMap (uncurry replicate)


What's is wrong with:

decode a b = replicate a b

?


Your decodeHelper has the wrong call signature. You may get better results from the compiler if you put in expected function signatures everywhere, so that the type checker can tell you where it went wrong.

Specifically, your expression (1 x) or (n x) fail to be of the type (char,int), so they don't match the type inside the list you're feeding it. You need for these to be (1,x) and (n,x) to actually make the pattern match work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜