Link to Snippet

Combinator for tail-recursive functions

The snippet defines a combinator 'tailrec' that can be used to express tail-recursive functions. If you use 'tailrec' and do not mark your function as recursive, then the function will be a tail-recursive one.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15:

/// Implements a tail-recursive looping. The argument is a function/// that returns either Choice1Of2 with the final result or /// Choice2Of2 with new set of arguments.letrectailrecargsf=matchfargswith
| Choice1Of2res->res
| Choice2Of2newArgs->tailrecnewArgsf/// Tail-recursive function to sum the list written using 'tailrec'/// (note - this function is *not* marked as recursive itself)letsumListlist=tailrec (list, 0) (fun (list, acc) ->matchlistwith
| [] ->Choice1Of2acc
| x::xs->Choice2Of2 (xs, x+acc))

val tailrec : args:'a -> f:('a -> Choice<'b,'a>) -> 'b

Full name: Script.tailrec

Implements a tail-recursive looping. The argument is a function that returns either Choice1Of2 with the final result or Choice2Of2 with new set of arguments.

val args : 'a

val f : ('a -> Choice<'b,'a>)

union case Choice.Choice1Of2: 'T1 -> Choice<'T1,'T2>

val res : 'b

union case Choice.Choice2Of2: 'T2 -> Choice<'T1,'T2>

val newArgs : 'a

val sumList : list:int list -> int

Full name: Script.sumList

Tail-recursive function to sum the list written using 'tailrec' (note - this function is *not* marked as recursive itself)