Quantcast
Channel: Active questions tagged ocaml - Stack Overflow
Viewing all articles
Browse latest Browse all 595

A typical bracket balanced problem in ocaml

$
0
0

I'm trying to create a function which returns a boolean value to see if the string is balanced. But the result is just not what I expect. Can someone point out what I did wrong?

For example:

false = is_balanced")("false = is_balanced "(a)b)"true = is_balanced "fo"true = is_balanced "a(b(c)d)e"
let rec list_car ch = match ch with  | "" -> []  | ch -> (String.get ch 0 ) :: (list_car (String.sub ch 1 ( (String.length ch)-1) ) )  ;;let is_balanced klm =  let brk = list_car klm in  let rec left = function    | x::xs, 0 ->       if x = ')' then false       else left (xs, 0)    | x::xs, level ->       if x = '(' then left (xs, succ level)       else if x = ')' then left (xs, pred level)       else left (xs, level)    | [], level -> if level = 0 then true else false  in   left (brk, 0) ;;

But I got the following results:

is_balanced "(((";;- : bool = true is_balanced "()";;- : bool = false

Viewing all articles
Browse latest Browse all 595


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>