John Smith
John Smith

Reputation: 633

Addition in SML using pattern matching

I'm learning sml for the first time and I'm not too sure about the syntax for pattern matching.

As practice, I've tried to make some simple programs about binary numbers.

datatype Digit = Zero | One
type Nat = Digit list

fun inc [] = One::[]
| inc (Zero::rest) = (One::rest)
| inc (One::rest) = Zero::inc(rest)

fun dec [] = []
| dec (One::rest) = (Zero::rest)
| dec (Zero::rest) = One::dec(rest)


fun add (ds1, ds2) =
    let 
    fun addition ([],[],Zero) = []
            | addition (ds1, [], Zero) = ds1
            | addition ([], ds2, Zero) = ds2
            | addition (One, Zero, Zero) = (One::ds1)
            | addition (One, Zero, One) = Zero::addition(ds1,ds2,One)
            | addition (Zero, One, Zero) = (One::ds1)
            | addition (Zero, One, One) = Zero::addition(ds1,ds2,One)
            | addition (Zero, Zero, Zero) = (Zero::ds1)
            | addition (Zero, Zero, One) = (One::ds1)
            | addition (One, One, Zero) = Zero::addition(ds1,ds2,One)
            | addition (One, One, One) = One::addition(ds1,ds2,One)
    in
      addition(ds1, ds2, Zero)
    end

The first two work find but I can't get the addition to work. The point of the third function is to add binary numbers and return a list of the digits.

Any help is appreciated. Thanks

Upvotes: 0

Views: 616

Answers (1)

pad
pad

Reputation: 41290

The mistake in addition is that One and Zero are not lists so they are incompatible with [], ds1 and the like.

You have done nicely with inc and dec. I think you can employ the same pattern for add and make use of inc which you have created:

fun add (ds1, []) = ds1
  | add ([], ds2) = ds2
  | add (Zero::ds1, d::ds2) = d::add(ds1, fs2)
  | add (One::ds1, Zero::ds2) = One::add(ds1,ds2)
  | add (One::ds1, One::ds2) = Zero::inc(add(ds1,ds2))

Upvotes: 1

Related Questions