Haskell fillZeros program

Viewed 91

the program adds n number of zeros to the list x example

fillZeros "100" 1 "0100" fillZeros "10" 4 "000010"

my code :

fillZeros :: (Eq a, Num a) => [Char] -> a -> [Char] 
fillzeros x 0 = x 
fillzeros (x:xs) a  = (0:fillzeros (x:xs) a-1)

Missing binding for variable "fillZeros" in type signature this error appears every time I reload :r

1 Answers

The first problem you encounter is that you specify the signature for a function fillZeros (with uppercase Z), but your implementation is for a function fillzeros (with lowercase z).

Furthermore it makes no sense to use (0: fillzeros (x:xs) a-1): this is parsed as (0: (fillzeros (x:xs) a) - 1), so you subtract one from the recursive call, and furthermore 0 is not a Char so you can not use that in your function.

In order to pattern match, it is better to match with x, otherwise fillzeros "" 15 will raise an error, because the empty string does not match with (x:xs).

You thus implement this with:

fillzeros :: (Eq a, Num a) => [Char] -> a -> [Char] 
fillzeros x 0 = x 
fillzeros x a  = ('0' : fillzeros x (a-1))
Related