A simple parenthesis counter

45 views
Skip to first unread message

edA-qa mort-ora-y

unread,
Oct 28, 2017, 11:21:53 AM10/28/17
to Leaflang

Saw a simple test at https://dev.to/yechielk/parenthetically-speaking-1b and decided to code it.


import std

var main = -> {
	check( "(a)" )
	check( "a(b)(c)()" )
	check( "((()))" )
	check( "(()())" )
	check( "(()(()))" )
	check( "(" )
	check( "(()" )
	check( "(())()((" )
	check( ")(q" )
	check( "(()))(" )
	check( "okay" )
}

defn check = (text : arraychar」) -> {
	var r = parentheses_checker(text)
	not r then {
		std.println([ text, " ✗" ])
	} else {
		std.println([text, " ✓"])
	}
}

defn parentheses_checker = (text : arraychar」) -> {
	var open = 0
	
	for i in std.range(0, text.size) {
		var c = text#i
		do select(
			c == '(' ? {
				open += 1
			}, c == ')' ? {
				open -= 1
			}
		)
		open < 0 then return false
	}

	return open == 0
}


Had a bit of a problem with this bit at the start:


    //TODO: error: func.instances() < 10
     foreach( [ "()", "()()()", "((()))", "(()())",
         "(()(()))", "(", "(()", "(())()((", ")(", "(()))(" ], (s)-> {
         check( s )
     })

Iteration over a tuple in this fashion should have worked. :/

Reply all
Reply to author
Forward
0 new messages