Can you please help me with this:
I have 2 functions:
f1: Int => Boolean
f2: Int => Boolean
now I want to combine/merge these functions with logical OR, something like:
f3: Int => f1 || f2
so function f3 will return true only if one of functions f1 and f2 returns true
how to write such function?
thanks a lot
def f3(n:Int) = f1(n) || f2(n)
So this is a good bit of infrastructure, but I've found it useful in the past to actually add boolean operations as effectively native operations on predicates. It's one of the things I keep in my grab-bag of utility functionality, and eventually import into pretty much every project I write.
object PredicateUtils {
implicit class RichPredicate[A](f: Function1[A, Boolean]) extends Function1[A, Boolean] {
def apply(v: A) = f(v)
def &&(g: Function1[A, Boolean]): Function1[A, Boolean] = {
(x: A) => f(x) && g(x)
}
def ||(g: Function1[A, Boolean]): Function1[A, Boolean] = {
(x: A) => f(x) || g(x)
}
def unary_! : Function1[A, Boolean] = {
(x: A) => !f(x)
}
}
}
Once you've done that, then all you have to do is
import PredicateUtils
val f3 = f1 || f2
val f4 = !f1 && f2
That would be:
def union(f: Int => Boolean, g: Int => Boolean): Int => Boolean= { x => f(x) || g(x)}
The question here is from where comes 'x', isn't it? Well... it would be the same question as if you ask where f or g come from. You don't even think about that, those are parameters and that suffices. Same answer applies. Forget about the rest of the function. Does x => f(x) || g(x) make sense? As long as f and g return boolean it does, doesn't it? So there you are.
I would say that if you read the whole function from inside out, it has obvious meaning.
Cheers!
def fun_or[T](f1: T => Boolean, f2: T => Boolean)(x: T) = f1(x) || f2(x)
then:
val f3 = fun_or(f1, f2)
examples of composing predicates: http://danielwestheide.com/blog/2013/01/23/the-neophytes-guide-to-scala-part-10-staying-dry-with-higher-order-functions.html
Related
Is it possible, in Scala, to define a function that would receive any other function as a parameter?
It should be something like the following:
object Module extends SecureModule{
val bc = new MyBC()
def method(parameter: Type) = {
exec(bc.method(parameter))
}
def method2(parameter1: Type1, parameter2: Type2) = {
exec(bc.method2(parameter1,parameter2))
}
}
trait SecureModule {
def exec(f: ANY_PARAMETER => ANY_RESULT) = {
//some extra processing
f
}
}
is it possible? If so, how could I achieve this?
Thank you in advance.
The nice thing about scala is that you can create what seems to be your own syntax.
If what you want to do is wrap an operation so that you can do pre and post processing, as well as control the execution context, then you do this by using call-by-name parameters. For example, if we just wanted to time how long a block of code takes, then we could do something like this:
def timer[T](block: => T): (T,Long) = {
val startDate = new Date()
val result = block
val endDate = new Date()
(result, endDate.getTime()-startDate.getTime())
}
We can use it like this:
val (result,duration) = timer {
1+3
}
Or like this
val (result,duration) = timer {
"hello" + " world!"
}
And the result will have the correct type from the block that you pass in while also giving you the duration that you expect.
I am under the impression that your description is somewhat misleading.
The way I understand it, what you (might) want to do is delaying the execution of the bc.method calls until some other code has been performed.
If so, try this:
object Module extends SecureModule{
val bc = new MyBC()
def method(parameter: Type) = {
exec(() => bc.method(parameter))
}
def method2(parameter1: Type1, parameter2: Type2) = {
exec(() => bc.method2(parameter1,parameter2))
}
}
trait SecureModule {
def exec[Result](f: () => Result): Result = {
//some extra processing
f()
}
}
You can't take any function as a parameter. What would you even do it?
At best, you can take any function that has a specific number of parameters.
For example, here, f takes one argument and returns a value.
def exec[A,B](f: A => B)
And here, f takes two arguments:
def exec[A,B,C](f: (A, B) => C)
If you don't care about the return type of the function, you could always use Any instead of a type parameter, since functions are covariant in their return type:
def exec[A](f: A => Any)
How do I create this function which returns true if a number is 5 to an anonymous function:
def yeah_five(p: Int): Boolean = p == 5
thanks?
Short notation for anonymous functions:
(p: Int) => (p == 5);
Long version:
new Function1[Int] {
def apply(p: Int): Int = p == 5
}
You want a function that takes an Integer and returns a Boolean
(p: Int) => (p == 5);
Read through the tutorial on anonymous functions.
I guess the shortest way to write it would be like so:
val f: Int => Boolean = (_ == 5)
Of course, depending on the context you can loose the type annotation:
List(1, 2, 3, 5, 4, 5).filter(_ == 5)
=> List(5, 5)
As per #Senia's observation you can be even more succint with 5== wich transforms the == method of the object 5 to a function.
val g: Int => Boolean = 5==
List(1, 2, 3, 5, 4, 5).filter(g) => List(5, 5)
In case you are want to turn that already declared method into a function, do this
yeah_five _
The spray-json library extends basic Scala types with a toJson method. I'd like to convert an Any into a JsValue if there is such a pimp for the underlying type. My best attempt works, but is verbose:
import cc.spray._
val maybeJson1: PartialFunction[Any, JsValue] = {
case x: BigDecimal => x.toJson
case x: BigInt => x.toJson
case x: Boolean => x.toJson
case x: Byte => x.toJson
case x: Char => x.toJson
case x: Double => x.toJson
case x: Float => x.toJson
case x: Int => x.toJson
case x: Long => x.toJson
case x: Short => x.toJson
case x: String => x.toJson
case x: Symbol => x.toJson
case x: Unit => x.toJson
}
Ideally, I'd prefer something (impossible) like this:
def maybeJson2(any: Any): Option[JsValue] = {
if (pimpExistsFor(any))
Some(any.toJson)
else
None
}
Is there a way to do this without enumerating every type that has been enriched?
There is a way, but it requires a lot of reflection and therefore is quite a headache. The basic idea is as follows. The DefaultJsonProtocol object inherits a bunch of traits that contain implicit objects which contain write methods. Each of those will have an accessor function, but you won't know what it's called. Basically, you'll just take all methods that take no parameters and return one object that has a write method that takes the class of your object and returns a JsValue. If you find exactly one such method that returns one such class, use reflection to call it. Otherwise, bail.
It would look something like this (warning, untested):
def canWriteMe(writer: java.lang.Class[_], me: java.lang.Class[_]):
Option[java.lang.reflect.Method] =
{
writer.getMethods.find(_.getName == "write").filter{ m =>
classOf[JsValue].isAssignableFrom(m.getReturnType) && {
val parm = m.getParameterTypes()
m.length == 1 && parm(0).isAssignableFrom(me)
}
}
}
def maybeJson2(any: Any): Option[JsValue] = {
val couldWork = {
DefaultJsonProtocol.getClass.getMethods.
filter(_.getParameterTypes.length==0).
flatMap(m => canWriteMe(m.getReturnType, any.getClass).map(_ -> m))
}
if (couldWork.length != 1) None else {
couldWork.headOption.map{ case (wrMeth, obMeth) =>
val wrObj = obMeth.invoke(DefaultJsonProtocol)
val answer = wrMeth.invoke(wrObj, any)
}
}
}
Anyway, you're best off pulling the DefaultJsonProtocol class apart in the REPL step by step and finding out how to reliably identify the objects that define the writers, and then get the write methods out of them.
I'm not sure it will fit you needs, but here is an alternative approach wich is really simple and type-safe.
If you kept the type of the argument (instead of using Any) you could rely on implicit parameter resolution to find the correct conversion at compile time:
def toJson[T:JsonFormat]( t: T ): JsValue = implicitly[JsonFormat[T]].write(t)
You won't need an option, because the program will fail at compile time if you try to pass an argument which is not "pimpable".
I've got a function which loads various models, and currently have this kind of setup:
if(message == "user") {
var model = User.findAll(
("room" -> "demo")
)
} else if (message == "chat") {
var model = Chat.findAll(
("room" -> "demo")
)
}
This is really clunky as I aim to add lots more models in future, I know in javascript you can do something like this:
var models = {
"user" : load_user,
"chat" : load_chat
}
Where "load_user" and "load_chat" would load the respective models, and so I can streamline the whole thing by doing:
var model = models[message]();
Is there a way I can do something similar in Scala, so I can have a simple function which just passes the "message" var to a List or Object of some kind to return the relevant data?
Thanks in advance for any help, much appreciated :)
In Scala you can do:
val model = message match {
case "user" => loadUser() // custom function
case "chat" => loadChat() // another custom function
case _ => handleFailure()
}
You can as well work with a Map like you did in your JavaScript example like so:
scala> def loadUser() = 1 // custom function
loadUser: Int
scala> def loadChat() = 2 // another custom function
loadChat: Int
scala> val foo = Map("user" -> loadUser _, "chat" -> loadChat _)
foo: scala.collection.immutable.Map[java.lang.String,() => Int] = Map(user -> <function0>, chat -> <function0>)
scala> foo("user")()
res1: Int = 1
Pay attention to the use of "_" in order to prevent evaluation of loadUser or loadChat when creating the map.
Personally, I'd stick with pattern matching.
While reading the description of Functors on this blog:
https://hseeberger.wordpress.com/2010/11/25/introduction-to-category-theory-in-scala/
there is a generic definition of Functor and a more specific one:
trait GenericFunctor[->>[_, _], ->>>[_, _], F[_]] {
def fmap[A, B](f: A ->> B): F[A] ->>> F[B]
}
trait Functor[F[_]] extends GenericFunctor[Function, Function, F] {
final def fmap[A, B](as: F[A])(f: A => B): F[B] =
fmap(f)(as)
}
Clearly this means Functors can be used with other higher-kinded types besides Function objects. Could someone please give an example or explain how or why or in what scenario that would be done? Namely, what would another implementation of GenericFunctor be in Scala -- that uses a different type constructor from Function? Thanks!
EDIT:
Just to clarify:
object Functor {
def fmap[A, B, F[_]](as: F[A])(f: A => B)(implicit functor: Functor[F]): F[B] =
functor.fmap(as)(f)
implicit object ListFunctor extends Functor[List] {
def fmap[A, B](f: A => B): List[A] => List[B] =
as => as map f
}
}
scala> fmap(List(1, 2, 3))(x => x + 1)
res0: List[Int] = List(2, 3, 4)
Just to clarify, according to my understanding ListFunctor implements the 1-arg fmap in GenericFunctor while the code in the repl transcript calls the fmap in Trait Functor, which in turn calls an fmap implementation (e.g. in ListFunctor).
This doesn't change the overall question, just thought it would help people trying to provide answers. Any insights provided would be appreciated.
In your example Functor is an endofunctor in the category of Scala types with Function1 as arrows.
There are other categories. For example, imagine a category in which the objects are Scala types, and there is an arrow A >~> B if B is a subtype of A. This category in Scalaz is called Liskov. There is a "forgetful" functor from the Liskov category to the Function1 category:
import scalaz._
import Scalaz._
trait Forget[F[-_]] extends GenericFunctor[>~>, Function1, F] {
def fmap[A, B](f: A >~> B): F[A] => F[B] = fa => f.subst(fa)
}
Note that you can build some interesting functors by fixing one or more of the arguments to GenericFunctor. For example...
A constant functor maps every object in one category to a single object in another:
type ConstantFunctor[->>[_, _], ->>>[_, _], C] =
GenericFunctor[->>,->>>,({type F[x] = C})#F]
// def fmap[A, B](f: A ->> B): C ->>> C
An endofunctor maps a category to itself:
type EndoFunctor[->>[_, _], F[_]] = GenericFunctor[->>, ->>, F]
// def fmap[A, B](f: A ->> B): F[A] ->> F[B]
An identity functor maps every object and arrow to itself:
type IdentityFunctor[->>[_, _]] = EndoFunctor[->>, ({type F[x] = x})#F]
// def fmap[A, B](f: A ->> B): A ->> B
And of course, your Functor trait is just an EndoFunctor in the Function1 category.
type Functor[F[_]] = EndoFunctor[Function1, F]
// def fmap[A, B](f: A => B): F[A] => F[B]
You can imagine a functor which lifts an instance of Either[A,B] into an Either[F[A],F[B]] where F can be a List, Option, etc.
EDIT Implementation example:
trait GenericFunctor[->>[_, _], ->>>[_, _], F[_]] {
def fmap[A, B](f: A ->> B): F[A] ->>> F[B]
}
trait EitherFunctor[F[_]] extends GenericFunctor[Either,Either,F]
object ListFunctor extends EitherFunctor[List] {
def fmap[A,B]( f: Either[A,B] ): Either[List[A],List[B]] =
f match {
case Left(a) => Left( List(a) )
case Right(b) => Right( List(b) )
}
}
EDIT2 Another (maybe useful) example is with a functor with goes from a PartialFunction (type ->>) to a Function (type ->>>):
trait PartialFunctor[F[_]]
extends GenericFunctor[PartialFunction,Function,F] {
final def fmap[A, B](as: F[A])(f: PartialFunction[A,B]): F[B] =
fmap(f)(as)
}
object OptionFunctor extends PartialFunctor[Option] {
def fmap[A,B]( f: PartialFunction[A,B] ): Option[A] => Option[B] =
(opt:Option[A]) => opt match {
case Some(a) => f.lift(a)
case None => None
}
}
object ListFunctor extends PartialFunctor[List] {
private def mapPartial[A,B]( f: PartialFunction[A,B], as: List[A] ): List[B] =
as match {
case Nil => Nil
case h :: t => if( f isDefinedAt h ) f(h) :: mapPartial( f, t )
else mapPartial( f, t )
}
def fmap[A,B]( f: PartialFunction[A,B] ): List[A] => List[B] =
(lst:List[A]) => mapPartial(f, lst)
}
This second example allows to implement the collect operation as defined in Scala collections:
def collect[A,B,F[_]]( as: F[A] )
( pf: PartialFunction[A,B] )
( implicit functor: PartialFunctor[F] ) =
functor.fmap( as )( pf )
Data.Category is a good source for examples of things like this (in Haskell). Partially translating one of the instances from http://hackage.haskell.org/packages/archive/data-category/0.4.1/doc/html/src/Data-Category-Functor.html:
type OpFun[A, B] = B => A
case class OpFunctor[F[_]](functor: Functor[F[_]]) extends GenericFunctor[OpFun, OpFun, F] {
def fmap[A, B](f: B => A): F[B] => F[A] = fb => functor.fmap(fb)(f)
}