0

I am trying to write a code such that, given a list of parenthesis, I will check if the order is valid or not.

For simpleness, the follwoing datatype is defined.

datatype par = LPAR | RPAR
 type pList = par list

What I have until now is:

fun valid(nil:plist): bool = true
| valid([Lpar]) = false
| valid([Rpar]) = false
| valid([Lrap,Rpar) = true
| valid(L::L1) =

For instance, "(()()"--> [Lpar,Lpar,Rpar,Lpar,Rpar] will return false You can see that the parenthesis is in string format. I am confused since I will have to check to two things: that the left ( are equal to the left ) and that each ( matches a ). If so then I will need to make some helper functions.

Can you please provide me with information about what my helper functions should be or a better implementation of this? ty

Sarah cartenz
  • 1,313
  • 2
  • 14
  • 37
  • First pattern is OK. Second, third and fourth pattern are rather useless, although not formally wrong. You seem to attempt to treat a list of parenthesis as a whole. Try to express this rule instead: a closing parenthesis comes after an opening parenthesis, and so recursively (inside an opening-closing pair, there may be nested opening-closing pairs). Is this for an assignment? – Hibou57 Sep 27 '14 at 23:21

2 Answers2

1

I have found out a way to solve my problem by counting the parenthesis. The logic goes like this:

I start from 0, if i find a left p I add 1, other wise I minus 1. Once I enter -1 i return false right away since I cannot have a right p come first. Then I recurse. If the final output is 0, the its true since this means that every left p matches a right p.

Q.E.D

Sarah cartenz
  • 1,313
  • 2
  • 14
  • 37
0

I didn't try this in the repl but it should look something like this

fun valid_paren xs : bool = 
fun aux (xs, ctr) = case xs of
    [] => ctr = 0
  | (x:xs') => case x of 
           '(' => aux (xs', ctr+1)
           ')' => aux (xs', ctr-1)
            _  => aux (xs', ctr)
in
  aux (xs, 0)
fr1c710n
  • 88
  • 1
  • 11