Ahmad
Ahmad

Reputation: 115

Construct binary numbers in haskell

I am newbie to Haskell programming language and I am trying to create a data type to represent binary numbers and write a function to evaluate its decimal value.

I want to represent this BNF for the binary numberals

Numeral ::= 0 | 1 | Numeral 0 | Numeral 1

I constructed its datatype in haskell using pattern matching and field labels like this

data Numeral = Zero | One | Num {number :: Numeral, suffex :: Int}

and I created a function

    valuate Zero = 0
    valuate One  = 1
    valuate Num(n:0) = 2 * valuate (n)
    valuate Num(n:1) = 2 * valuate (n) + 1
    valuate Num(n:ns) = error "Not binary number"

But I get a compile error "Exception for 'valuate' have different number of arguments"

I am trying to understand where is the mistake I did, I am passing Numeral to the method in every pattern with different construct value and even when I call (2*valuate n) I am passing "n" which is Numberal in the construct 'Num'

Is the issue in my datatype or the function patterns?

Upvotes: 0

Views: 402

Answers (1)

kini
kini

Reputation: 1803

You should write your function like this:

valuate Zero      = 0
valuate One       = 1
valuate (Num n 0) = 2 * valuate n
valuate (Num n 1) = 2 * valuate n + 1
valuate (Num n _) = error "Not binary number"

First of all, you need parentheses around complex patterns (just like when passing things as arguments to functions). Second, you seem to be using : to separate the arguments to Num. (:) is a constructor for lists, and doesn't make sense here.

I suggest you write function applications like f a rather than f(a) in the future, as that may help you get a better grasp of how precedence works in Haskell's syntax.

Upvotes: 5

Related Questions