【问题标题】:F# Discriminated Unions and PrintingF# 可区分联合和打印
【发布时间】:2018-06-09 20:56:43
【问题描述】:

我正在尝试解决以下问题,但很难弄清楚如何以所需的格式打印它,使用括号和数字/运算符。

我有下面的代码来创建表达式,但是使用匹配模式打印 %A 不起作用。我可以访问值,但无法以所需的格式打印它们。有人有建议吗?

let one = Const(1)
let two = Const(2)
let three = Const(3)
let Bin1 = BinOpr(one, "+", two)
let Bin2 = BinOpr(Bin1, "*", three)

【问题讨论】:

  • 我认为这对您自己弄清楚会很有启发性。作为提示,请注意它不是要求您打印,而是创建一个创建字符串的函数。您必须在该函数的输入上match 才能创建所需的输出。即let toString expr = match expr with | Const i -> ...

标签: f#


【解决方案1】:

解决这个问题的方法是在expr上通过模式匹配实现toString,并为ConstBinOpr输出相应的字符串:

  • 对于Const,您只需将int 转换为字符串。
  • 对于BinOpr,您必须构建(<expr> <op> <expr>) 形式的字符串。

尝试自己实现该功能,这并不难,但如果你卡住了,我提供下面的解决方案。


解决方案

let rec toString expr =
  match expr with
  | Const x -> string x
  | BinOpr (e1, op, e2) -> sprintf "(%s %s %s)" (toString e1) op (toString e2)

【讨论】:

    猜你喜欢
    • 2011-11-19
    • 2020-08-22
    • 1970-01-01
    • 2012-12-14
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 2013-08-04
    相关资源
    最近更新 更多