So I am trying to use f# to find if a string has matching parentheses. i.e: (abc) returns true, ((hello) returns false, and )( returns false, etc...
What I (think) am doing is using a stack to push when it sees a '(' and pop when it sees a ')' in the list. Then if the string list is empty, either the stack has an item or it doesn't. If it does, then I say that it is invalid, if I come across a ')' and the stack is empty, it is also invalid. Otherwise it is a valid string.
// Break string
let break_string (str:string) =
Seq.toList str
let isBalanced (str:string) =
let lst = break_string str
let stack = []
let rec balance str_lst (stk:'a list)=
match str_lst with
| [] ->
if stk.Length > 0 then
false
else
true
| x::xs ->
if x = '(' then
balance (xs x::stack)
elif x = ')' then
if stack.Length = 0 then
false
else
stack = stack.tail
balance (lst, stack)
I am pretty new to f# so I think this might be doing what I want, however I get the error message: "This expression was expected to have type bool but here has type 'a list -> bool"
First, what does that actually mean? Second, since it is returning a bool, why doesn't that work?
balance lst stack. That's how you call functions with multiple parameters in F#.(a,b)syntax creats a tuple. The same applies to recursive call. - MarcinJuraszek