Is it possible to get the domain of a Partial Function in Scala?
Ex:
val f: PartialFunction[Int, Unit] = {
case 1 => println("This is 1")
case 2 => println("This is 2")
}
Is there any way to get something like:
val list = f.getDomain
which would indicate values 1 and 2?
Update: I am trying to build an notification system (event bus). The subscriber will look like this:
class SomeSubscriber extends Subscriber {
notifications {
case LoginEvent(date) => println("Login on " + date)
case LogoutEvent(date) => println("Logout on " + date)
case e: Notification[Any] => async {
println("Other notification: " + e)
ui {
println("UI in async! " + e)
}
}
}
}
In my NotiticationService (the event dispatcher) I want to access the events declared in every 'notifications' block so I can push the notifications to the subscribers. How can I do that?
Thanks in advance.
// Creating Partial function1. val M : PartialFunction[Int, Int] = { // using case statement. case x if (x % 5 ) == 0 => x * 5.
Val functions inherit the andThen function and we will show how to use the andThen function to compose two functions together. Mathematically speaking, (f andThen g)(x) = g(f(x)). The results of the first function f(x) is ran first and will be passed as input to the second function g(x).
Many properties of functions can be extended in an appropriate sense of partial functions. A partial function is said to be injective, surjective, or bijective when the function given by the restriction of the partial function to its domain of definition is injective, surjective, bijective respectively.
Currying is a technique or a process for modifying a function in Scala. This function converts several parameters into a single argument function. Curried functions have multiple parameter lists. It is widely used in a wide range of functional languages.
If you have a collection, and you'd like to know which elements also belong to the domain of f
, you can use filter
and isDefinedAt
like so:
scala> 1 to 10 filter f.isDefinedAt
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2)
This simply checks exhaustively. I don't know if there is any better way.
It's inherently impossible, since a partial function may be defined for any subset of the input range; the input range itself may not be finite, in which case the domain would not necessarily be finite either. You can only obtain the domain via an exhaustive match (per Dan's answer), however you cannot exhaustively search an infinite input space.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With