简体   繁体   中英

Problem writing mutually recursive function in F#

I am translating a function from Little Mler that operates on this data type

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. It's expecting the name of the other function after the and which is why you're getting the error. 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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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