【问题标题】:Unable to call a function from recursive f#无法从递归 f# 调用函数
【发布时间】:2017-05-12 23:41:20
【问题描述】:

尝试 F#,今天学到了很多,不确定我是否正在尝试,但我有一个模式匹配和递归,由于某种原因我无法从递归调用它。

// Define my active recognizer for keywords
let(|MyGirlFriend|Bye|) input =
   match input with
   |"lonely|"love"|"friendship"
       -> MyGirlFriend
   |"goodbye"|"bye"|"go"|
      -> Bye
   |_ 
        -> None 

我认为上面的代码看起来是对的。

//recursive response function

 let rec response (token: string) (str: string) =
     match token with
     | Bye
         -> good_bye_response ()
     | RoomLocation 
        ->  sprintf "%s" "Your call is log. Do you wish to quit?"
     |_ when token.Contains("yes") ->  "good bye" 0
     |_ when token.Contains("no") -> answer_response () 
     | None when (str.IndexOf(" ") > 0) 
        -> response (str.Substring(0,str.IndexOf(" "))) 
                    (str.Substring(str.IndexOf(" ")+1))
     | None when (str.IndexOf(" ") < 0) 
        -> response str ""       

我的功能是:

let rec chat () =
    if Break = false then
    let valueInput = Console.ReadLine()
    printf "Helpdesk-BCU Response --> %s \n" (response "" valueInput)
    if Break = false then 
    chat()
    else
      ChatEnd()

 let BCU_response (str: string) =
    if (str.IndexOf(" ") > 0) then
   response (str.Substring(0,str.IndexOf(" "))) (str.Substring(str.IndexOf(" 
   ")+1)) + "\n"
   else
      response str "" + "\n"

这里有几个问题 |_ when token.Contains("yes") -> "goodbye" 0 F# 中用作出口的零在这里我得到一条红线,它指出表达式应该具有类型字符串但有 int 类型,我知道零是 int。

那么我该如何退出递归循环呢?

欢迎任何建议

【问题讨论】:

  • 缩进已关闭。请更正。

标签: f# functional-programming


【解决方案1】:

目前尚不清楚您在为哪一部分苦苦挣扎,因为代码中有很多小问题。然而,一个展示如何进行递归的最小工作示例是这样的:

open System

let (|Bye|Other|) input =
  match input with
  | "goodbye" | "bye" | "go" -> Bye
  | _ -> Other

let response (token: string) =
  match token with
  | Bye -> false, "bye!"
  | Other -> true, "sorry, I didn't get that"

let rec chat () =
  let input = Console.ReadLine()
  let keepRunning, message = response input
  printfn ">> %s" message
  if keepRunning then chat ()

response 函数现在也返回一个布尔值 - 如果这是 truechat 函数会递归调用自身以提出另一个问题。否则,它只会返回而不询问更多问题。

【讨论】:

  • 谢谢你,我确实有很多东西要学,一旦你掌握了基本知识,这门语言就不会那么糟糕了。纠正我,递归在某种意义上是一个循环,它将继续以递归方式进行,直到 false 有点像 While(true) 做任何正确的事情?
  • 是的,递归非常像循环——你可以使用 while 循环和可变变量来编写 chat 函数,例如while running do ...。您需要使用 let mutable running = true 定义可变变量,并最终使用 running &lt;- false 将其设置为 false。
猜你喜欢
  • 2022-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-15
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多