I'm trying to convert a Haskell function, which displays a boolean formula, to a SML function.
The function:
data Formula
= Atom String
| Neg Formula
| Conj Formula Formula
| Disj Formula Formula
precedence :: Formula -> Int
precedence Atom{} = 4
precedence Neg {} = 3
precedence Conj{} = 2
precedence Disj{} = 1
displayPrec :: Int -> Formula -> String
displayPrec dCntxt f = bracket unbracketed where
dHere = precedence f
recurse = displayPrec dHere
unbracketed = case f of
Atom s -> s
Neg p -> "~ " ++ recurse p
Conj p q -> recurse p ++ " & " ++ recurse q
Disj p q -> recurse p ++ " | " ++ recurse q
bracket
| dCntxt > dHere = \s -> "(" ++ s ++ ")"
| otherwise = id
display :: Formula -> String
display = displayPrec 0
I' ve come so far as translating it to SML:
fun precedence(operator) =
case operator of
Atom a => 4
| Neg p => 3
| Conj(p,q) => 2
| Disj(p,q) => 1
fun displayPrec dCntxt f =
let
val dHere = precedence f
val recurse = displayPrec dHere
val unbracketed = case f of
Atom a => a
| Neg p => "~ " ^ recurse p
| Conj(p,q)=>(recurse p) ^ " & " ^ (recurse q)
| Disj(p,q)=>(recurse p) ^ " | " ^ (recurse q)
(* missing bracket function *)
in
(* bracket *) unbracketed
end
The unbracketed function works. It shows the formula without braces. The only thing that is still missing is the bracket function, which I don't know what it does and how to translate it to SML. Can someone, who is more experienced, help me with this?
That would be
The function compares the precedence level of your context against the precedence level of the outer operator of your expression and decides to either insert a pair of parentheses around the given string or not.