Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
F#:如何将表达式转换为字符串_F#_Tostring - Fatal编程技术网

F#:如何将表达式转换为字符串

F#:如何将表达式转换为字符串,f#,tostring,F#,Tostring,您好,我有一个问题: 编写一个F#函数toString:aexpr->string来格式化表达式 作为字符串,使用以fix格式编写的二进制运算符。对于 例如,它可以将Sub(Var“x”,CstI 34)格式化为字符串“x”- 34". 为简单起见,在任何子表达式(即使是 根据标准的优先规则,它们是超丰满的 用于算术运算符。使用预先定义的函数字符串进行转换 将整数值转换为其字符串表示形式 提示:toString与eval函数的结构非常相似, 尽管它不需要环境参数,因为它使用变量 名称,而不是变量

您好,我有一个问题:

编写一个F#函数toString:aexpr->string来格式化表达式 作为字符串,使用以fix格式编写的二进制运算符。对于 例如,它可以将Sub(Var“x”,CstI 34)格式化为字符串“x”- 34". 为简单起见,在任何子表达式(即使是 根据标准的优先规则,它们是超丰满的 用于算术运算符。使用预先定义的函数字符串进行转换 将整数值转换为其字符串表示形式

提示:toString与eval函数的结构非常相似, 尽管它不需要环境参数,因为它使用变量 名称,而不是变量值

是的,这是一个硬件问题。如有任何帮助,请解释。下面我包含了一个eval函数

以下是我们一直使用的数据类型:

type oper1 = Neg | Not
type oper2 = Add | Mul | Sub | Less | Eq | And

type aexpr = 
  | C of int
  | V of string
  | Op1 of oper1 * aexpr
  | Op2 of oper2 * aexpr * aexpr

let rec eval e (env : (string * int) list) : int =
  match e with
  | CstI i            -> i
  | Var x             -> lookup env x 
  | Prim("+", e1, e2) -> (eval e1 env) + (eval e2 env)
  | Prim("*", e1, e2) -> (eval e1 env) * (eval e2 env)
  | Prim("-", e1, e2) -> (eval e1 env) - (eval e2 env)
  | Prim _ -> failwith "unknown primitive"
  | Let(x, e1, e2) -> eval e2 ((x, eval e1 env) :: env)
对于给定的问题,我写了:

let rec toString e (env : (string * int) list) : string
   match e with 
   | Prim("+", e1, e2) -> "e1 + e2"
   | Prim("*", e1, e2) -> "e1 - e2"
   | Prim("-", e1, e2) -> "e1 * e2"
这可能看起来很愚蠢,或者我的思路正确吗?对于F#

来说,这是一个相当新的问题,它指出:

[…]尽管它不需要环境参数[…]

因此,您的函数
toString
应该如下所示:

let rec toString e =
    match e with
    | CstI i            -> sprintf "%i" i // format number as string
    | Var  x            -> x              // already a string
    | Prim("+", e1, e2) -> sprintf "(%s + %s)" (toString e1) (toString e2)
    | Prim("*", e1, e2) -> sprintf "(%s * %s)" (toString e1) (toString e2)
    | Prim("-", e1, e2) -> sprintf "(%s - %s)" (toString e1) (toString e2)

对于嵌套表达式,首先对子表达式调用
toString
。然后将生成的字符串插入
%s
中的
sprintf

我想你要写的是e1和e2的特定值,而不仅仅是名称,你必须递归地写,因为我想这些都是表达式。谁分配了F#作业?幸运!幸运??哈哈,不是粉丝