将Haskell函数转换为SML

 陈旺财九_999 发布于 2023-02-12 14:54

我正在尝试将显示布尔公式的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

我到目前为止已将其翻译为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

无括号的功能有效.它显示了没有括号的公式.唯一仍然缺少的是括号函数,我不知道它的作用以及如何将其转换为SML.有经验的人可以帮助我吗?

1 个回答
  • 那就是

    val bracket =
      if dCntxt > dHere
      then fn s => "(" ^ s ^ ")"
      else fn x => x
    

    该函数将上下文的优先级与表达式外部运算符的优先级进行比较,并决定是否在给定字符串周围插入一对括号.

    2023-02-12 14:58 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有