【问题标题】:fsharp function doesn't return anythingfsharp 函数不返回任何内容
【发布时间】:2015-02-13 06:08:44
【问题描述】:

对于简单的算术表达式,我有以下较小的标记器。我是 fsharp 的新手,我不知道为什么这个函数在被调用时不返回任何内容。有人可以帮忙吗?

let tokenizer s = 
  let chars1 = scan s
  let rec repeat list = 
    match list with
    | []->[]
    | char::chars ->
      match char with
      | ')' -> RP::repeat chars
      | '(' -> LP::repeat chars
      | '+' -> Plus::repeat chars
      | '*' -> Times::repeat chars
      | '^' -> Pow::repeat chars
      | _ -> 
        let (x,y) = makeInt (toInt char) chars
        Int x::repeat chars
  repeat chars1

【问题讨论】:

  • 您有任何示例输入和预期输出吗?
  • @MarcinJuraszek 如果我输入类似 1+2 的内容,我至少应该有一些输出。但是现在我的代码没有任何输出。
  • 您是否尝试过在调试器中单步执行?查看代码,似乎 repeat 可以返回空列表的唯一方法是如果 list 在第一次调用 repeat 时为空,这意味着您的扫描功能失败。

标签: recursion f#


【解决方案1】:

scantoIntmakeInt的实现和表达式的联合类型没有给出,但可以推断为:

let scan (s:string) = s.ToCharArray() |> Array.toList
let toInt c = int c - int '0'
let makeInt n chars = (n,chars)

type expr = RP | LP | Plus | Times | Pow | Int of int

let tokenizer s = 
  let chars1 = scan s
  let rec repeat list = 
    match list with
    | []->[]
    | char::chars ->
      match char with
      | ')' -> RP::repeat chars
      | '(' -> LP::repeat chars
      | '+' -> Plus::repeat chars
      | '*' -> Times::repeat chars
      | '^' -> Pow::repeat chars
      | _ -> 
        let (x,y) = makeInt (toInt char) chars
        Int x::repeat chars
  repeat chars1

在这种情况下:

tokenizer "1+1"

给予:

val it : expr list = [Int 1; Plus; Int 1]

问题可能出在您的扫描功能的实现中。

【讨论】:

    猜你喜欢
    • 2018-08-27
    • 1970-01-01
    • 2021-12-22
    • 2017-06-23
    • 2016-08-10
    • 2022-01-12
    • 2020-01-10
    • 2021-07-23
    • 2022-01-09
    相关资源
    最近更新 更多