简体   繁体   English

在F#中编写相互递归函数时出现问题

[英]Problem writing mutually recursive function in F#

I am translating a function from Little Mler that operates on this data type 我正在翻译来自Little Mler的对此数据类型进行操作的函数

type sexp<'T> = 
    An_Atom of 'T
    | A_slist of slist<'T>
and 
    slist<'T> = 
    Empty
    | Scons of sexp<'T> * slist<'T>

The function 功能

// occurs_in_slist : aVal slist -> int
// checks the number of occurrence for aVal in slist

let rec occurs_in_slist =
    function
    _, Empty-> 0
   | (aVal : 'T), Scons(aSexp, (aSlist : 'T)) -> 
    occurs_in_sexp (aVal, aSexp) + occurs_in_slist (aVal, aSlist)
and
   aVal, An_Atom (bVal) ->  if (aVal = bVal) then 1 else 0
   |  (aVal , A_slist(aSlist)) -> occurs_in_slist (aval, aSlist)

However, I get this error for the second function 但是,第二个功能却出现此错误

error FS0010: Unexpected symbol '->' in binding. Expected '=' or other token.

In your function definition, you've used the and keyword to define a mutually recursive set of functions however you've only given a name for the first function. 在函数定义中,您使用了and关键字定义了一组相互递归的函数,但是仅给第一个函数指定了名称。 It's expecting the name of the other function after the and which is why you're getting the error. 它的后预计其它功能的名称and这就是为什么你得到错误。 Unfortunately you've left that out. 不幸的是,您忽略了这一点。

I believe this is what you were trying to do: 我相信这是您想要做的:

let rec occurs_in_slist = function
  | _        , Empty -> 0
  | aVal : 'T, Scons(aSexp, aSlist : slist<'T>) -> 
        occurs_in_sexp (aVal, aSexp) + occurs_in_slist (aVal, aSlist)
and occurs_in_sexp = function
  | aVal : 'T, An_Atom(bVal) -> if (aVal = bVal) then 1 else 0
  | aVal     , A_slist(aSlist) -> occurs_in_slist (aVal, aSlist)

Though I feel the more appropriate return type here should be a bool . 尽管我觉得这里更合适的返回类型应该是bool

let rec occurs_in_slist = function
  | _        , Empty -> false
  | aVal : 'T, Scons(aSexp, aSlist : slist<'T>) -> 
        occurs_in_sexp (aVal, aSexp) || occurs_in_slist (aVal, aSlist)
and occurs_in_sexp = function
  | aVal : 'T, An_Atom(bVal) -> aVal = bVal
  | aVal     , A_slist(aSlist) -> occurs_in_slist (aVal, aSlist)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM