Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit type recursion in F#

Inspired by this question:

Is explicit type recursion possible in F#?

type 'a Mu = In of 'a Mu 'a

let unIn (In x) = x

This code unfortunatly gives "Type parameter cannot be used as type constructor.

Remarks: This construct is used in the paper Functional Programming with Overloading and Higher-Order Polymorphism, for example.

Example of usage (taken from here):

type ('a, 'b) ListX =
    | Nil
    | Cons of 'a * 'b

type 'a List = ListX Mu
like image 772
Thomas Danecker Avatar asked Aug 10 '09 06:08

Thomas Danecker


People also ask

Does F# have tail recursion?

It's common to write F# code that recursively processes something with an inner and outer function, as the previous example shows. The inner function uses tail recursion, while the outer function has a better interface for callers.

Which keyword is used to define a recursive function?

Answer: The rec keyword is used together with the let keyword to define a recursive function.

What is recursive function in programming?

In programming terms, a recursive function can be defined as a routine that calls itself directly or indirectly. Using the recursive algorithm, certain problems can be solved quite easily. Towers of Hanoi (TOH) is one such programming exercise.


1 Answers

No, this is not possible. Specifically, generics in F# have the same limitation as the CLR, namely a <T> or an <'a> must have kind " * ". This same limitation is what means you cannot author "type classes" directly in F#, since e.g. "Monad m" would take a higher-kinded argument 'm' (e.g. "* -> *", where e.g. 'list' and 'option' could be instances, those each themselves being generic type constructors), but this is not allowed.

like image 104
Brian Avatar answered Oct 14 '22 06:10

Brian