Are there any example of Mutual recursion?

前端 未结 8 946
迷失自我
迷失自我 2021-02-04 09:48

Are there any examples for a recursive function that calls an other function which calls the first one too ?

Example :

function1()
{    
    //do something         


        
8条回答
  •  自闭症患者
    2021-02-04 10:14

    I can think of two common sources of mutual recursion.

    Functions dealing with mutually recursive types

    Consider an Abstract Syntax Tree (AST) that keeps position information in every node. The type might look like this:

    type Expr =
      | Int of int
      | Var of string
      | Add of ExprAux * ExprAux
    and ExprAux = Expr of int * Expr
    

    The easiest way to write functions that manipulate values of these types is to write mutually recursive functions. For example, a function to find the set of free variables:

    let rec freeVariables = function
      | Int n -> Set.empty
      | Var x -> Set.singleton x
      | Add(f, g) -> Set.union (freeVariablesAux f) (freeVariablesAux g)
    and freeVariablesAux (Expr(loc, e)) =
      freeVariables e
    

    State machines

    Consider a state machine that is either on, off or paused with instructions to start, stop, pause and resume (F# code):

    type Instruction = Start | Stop | Pause | Resume
    

    The state machine might be written as mutually recursive functions with one function for each state:

    type State = State of (Instruction -> State)
    
    let rec isOff = function
      | Start -> State isOn
      | _ -> State isOff
    and isOn = function
      | Stop -> State isOff
      | Pause -> State isPaused
      | _ -> State isOn
    and isPaused = function
      | Stop -> State isOff
      | Resume -> State isOn
      | _ -> State isPaused
    

提交回复
热议问题