Nathan Kronenfeld
Nathan Kronenfeld

Reputation: 513

How can I define a recursive function type in scala?

I would like, in scala, to define a function type something like:

type RFcn: () => RFcn

but I can't figure out a syntax to get it to work. Does anyone know how to do this?

Upvotes: 1

Views: 106

Answers (2)

Nathan Kronenfeld
Nathan Kronenfeld

Reputation: 513

Sarvesh's answer triggered something in my mind that gave me what I wanted. It's pretty simple:

abstract class RFcn extends Function0[RFcn]

That does what I was trying to express.

Upvotes: 1

sarveshseri
sarveshseri

Reputation: 13985

Well... the thing is that a recursive function is not supposed to return a function. And this type RFcn = () => RFcn does not look like a recursive function. So your question seems inspired from a bit of mis-understanding about recursive functions and is kind of invalid.

This type RFcn = () => RFcn looks more like a naive attempt towards implementing a state representing some step in a potential Bottom (read as potentially infinite computation). And if that is what you are after then you can change your question accordingly and may be something like a State monad can be useful to you.

Not lets come to part that can be answered. In Scala, funtions are acutally instances of Function1, Function2... etc. So if you want to have a type that represents a function from unit to function you can write as follows,

type UnitToFunc1[P1, R] = () => Function1[P1, R]

type UnitToFunc2[P1, P2, R] = () => Function2[P1, P2, R]

Upvotes: 0

Related Questions