The*_*Kid 4 haskell functional-programming sml smlnj
我正在尝试将显示布尔公式的Haskell函数转换为SML函数.
功能:
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
Run Code Online (Sandbox Code Playgroud)
我到目前为止已将其翻译为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
Run Code Online (Sandbox Code Playgroud)
无括号的功能有效.它显示了没有括号的公式.唯一仍然缺少的是括号函数,我不知道它的作用以及如何将其转换为SML.有经验的人可以帮助我吗?
那就是
val bracket =
if dCntxt > dHere
then fn s => "(" ^ s ^ ")"
else fn x => x
Run Code Online (Sandbox Code Playgroud)
该函数将上下文的优先级与表达式外部运算符的优先级进行比较,并决定是否在给定字符串周围插入一对括号.