I am trying to set a default value to an anonymous function in scala and so for not able to find any solution. Hope some one would help me out in SO.
I have the following structure,
case class A(id:Int = 0)
case class B(a:A)
object B {
def func1(f:Int = 0)={
........
}
def func2(f:A => B = (how to give default value ?))={
case Nothing => {
//do something....
}
case _ => {
//do some other thing......
}
}
}
Basically, I want to make passing the parameter as optional. How can I achieve this?
Like any other default parameter:
scala> def test(f: Int => Int = _ + 1) = f
test: (f: Int => Int)Int => Int
scala> test()(1)
res3: Int = 2
or with String:
scala> def test(f: String => String = identity) = f
test: (f: String => String)String => String
scala> test()
res1: String => String = <function1>
scala> test()("Hello")
res2: String = Hello
Edit:
In case if you want to use a function provided by default, you have to use () explicitly, either Scala won't paste a default argument.
If you don't wanna use a default function and provide an explicit one, just provide it yourself:
scala> test(_.toUpperCase)("Hello")
res2: String = HELLO
Use an implicit parameter. Place an implicit value for the parameter in the object. This will be used unless you provide an explicit parameter or you have provided another implicit value in the calling scope.
case class A(id:Int = 0)
case class B(a:A)
object B {
implicit val defFunc: A => B = {a: A => new B(a) }
def func1(f:Int = 0)={
}
def func2(implicit func: A => B) = { ... }
}
The differences between this method and Alexlv's method are
This works with standalone functions as well as methods.
The scope rules allow for providing appropriate overrides in appropriate scopes. Alex's method would require subclassing or eta-expansion (with partial application) to change the default.
I offer this solution since you are already using an object. Otherwise, Alexvlv's example is simpler.
The other answers show how to provide some existing default value, but if you want the default to do nothing (as suggested by case Nothing) then you can use Option/None.
def func2(f:Option[A => B] = None)={
case Some(f) =>
//do something....
case None =>
//do some other thing......
}
func2()
func2( Some(_ + 1) )
Related
So, suppose, I want to provide a "catch all" fall back for a PartialFunction:
val foo: PartialFunction[Int, String] = { case 1 => "foo" }
val withDefault = foo orElse { _.toString }
This does not compile: missing parameter type for expanded function ((x$1) => x$1.toString).
This:
val withDefault = foo orElse { case x: Int => x.toString }
Does not compile either (same error).
This:
val withDefault = foo orElse { (x: Int) => x.toString }
fails with type mismatch; found : Int => String; required: PartialFunction[?,?]
The only way I could find to make it work is to spell out the whole thing:
val withDefault = foo orElse PartialFunction[Int, String] { _.toString }
Is there any better syntax for this? I mean, one without having to tell it that I am passing a partial function from int to string to where it expects to receive a partial function from in to string. This is not ambiguous at all, why do I have to do this?
Maybe you need applyOrElse:
val withDefault = foo.applyOrElse(_: Int, (_: Int).toString)
Or maybe you would like something like this:
implicit class PartialFunToFun[A,B](val f: PartialFunction[A,B]) extends AnyVal {
def withDefault(bar: A => B) = f.applyOrElse[A,B](_: A, bar)
}
and use it: foo.withDefault(_.toString)(1)
Also if you want to get just another PartialFunction you can use the next syntax:
val withDefault = foo.orElse[Int, String]{case x => x.toString}
The errors you encountered for the first two are not specific to orElse. They also occur when you attempt to define the same functions separately.
scala> { _.toString }
<console>:12: error: missing parameter type for expanded function ((x$1: <error>) => x$1.toString)
{ _.toString }
scala> { case x: Int => x.toString }
<console>:12: error: missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: ?
{ case x: Int => x.toString }
^
For the last one, you are defining a function rather than a PartialFunction, thus leading to the "type mismatch" since orElse expects a PartialFunction to be passed.
scala> { (x: Int) => x.toString }
res3: Int => String = $$Lambda$1127/2044272973#3d5790ea
The final thing I'll add is that orElse is meant as a way to union two PartialFunctions. _.toString in itself is not a PartialFunction, though you could create a PartialFunction that uses it. To me it sounds like you want to have a "default" result for all the values that foo is not defined for, so I think you actually want applyOrElse instead since that is its use case. See the API to learn more.
I found following syntax in scala which i dont understand
object Category {
def id[A]: A => A = a => a
}
Especially this part A = a => a
Who can it be translated in a more readable syntax
This line:
def id[A]: A => A = a => a
defines a method named id which has a type argument A.
The return type of the method is A => A, which is: a function that takes an A and returns an A.
The part after the =: a => a is the body of the id method. It's a function literal for a function that takes a value a and returns the same thing a.
The part that you are specifically asking about: A = a => a is not a part by itself. The A => A is the return type of the method id, and the a => a is the body of the method. Just like with any other method, the = between these two parts separates the method declaration from the method body.
You could write the same thing like this:
def id[A]: Function1[A, A] = a => a
It's a method that returns a function which takes an A and returns another A and the function it is returning is an identity (you get a variable a of type A and just return it):
scala> object Category {
| def id[A]: A => A = a => a
| }
defined module Category
scala> Category.id[Int]
res0: Int => Int = <function1>
scala> res0(0)
res2: Int = 0
Not sure what are you trying to achieve here to be honest.
Google didn't help me with this question, I hope that doesn't mean it is not possible:
In my class I want to have a method that has a signature defined, but the body is not defined (method1)
There will be many defined methods that satisfy this signature (impl1, impl2, impl3)
When I initialise the object, I will then choose (based on some criteria) which method implementation impl1, impl2, impl3 to assign to the function pointer method1
Basically I'm asking how I can have a function pointer that can point to any function satisfying its signature.
EDIT:
So, it turns out it is actually very straight forward:
var method: Int => Int = (x => x+1)
method = (x => x-1)
method = (x => x*2)
etc...
My problem before was that I was using "val" or "def" to define "method"
Not sure why this wasn't suggested directly. Many people favoured the way of having the function as a parameter to some secondary class then initialise that class with a specific implementation. Maybe there is something that I'm missing.
EDIT 2: I realise now that I didn't get the answer I was looking for because I didn't word my question properly, I should have said that I wanted "delegate" behaviour as it is in C#.
In Scala, functions are objects, so you can do:
class Foo(val func : Int => Int){
}
object Main{
def main(args: Array[String]) {
val foo1=new Foo(x => x + 1)
val foo2=new Foo(x => x + 2)
val foo3=new Foo(x => x + 3)
println(foo1.func(10)) // Prints 11
println(foo2.func(10)) // Prints 12
println(foo3.func(10)) // Prints 13
}
}
And here is not-so-elegant approach with inheritance:
abstract class Foo() {
def say(): String
protected def bark = "Woof!"
protected def quack = "Quack!"
}
val dog = new Foo() {
def say() = bark
}
dog.say
// res2: String = Woof!
You mean like so:
class Whatever(selector: Int) {
type Signature = Int => String
private val implUsed = selector match {
case 1 => impl1
case _ => impl2
}
private val impl1: Signature = (i: Int) => i.toString
private val impl2: Signature = (i: Int) => i.toString + "_suffix"
def method: Signature = implUsed
}
You could obviously also write the impls as defs. Maybe a different approach based on inheritance may be preferrable though -- you may want to clarify what you are trying to achieve. While this approach is a literal solution to your request, it would be much more idiomatic to pass around the functions itself, like #Idan Arye suggested.
I would not use a method at all in this case. Just have a field that can be initialized to the specific function you want. Something like:
class Foo(val method1: Int => Int)
val doubler = new Foo(2*)
val incrementer = new Foo(1+)
val absolute = new Foo(_.abs)
val parity = new Foo(_ % 2)
val doesNothing = new Foo(identity)
doubler.method1(-3) // => -6
incrementer.method1(-3) // => -2
absolute.method1(-3) // => 3
parity.method1(-3) // => -1
doesNothing.method1(-3) // => -3
What would be the best and/or easiest way to extract a value that I've saved in a case class?
take for example the following code:
abstract class Something
case class Foo(input: Int) extends Something
case class Bar(input: Double) extends Something
def someMethod(a: Something, b: Something) {
// code that extracts values goes here
}
someMethod(Foo(10), Foo(20))
someMethod(Bar(2.1), Bar(21.2))
how would I then go about getting the integer or the double itself out of a and b when I call the method like I did under its definition?
Note that both the parameters are used in the same equation
In case classes constructor arguments are vals, so just call:
a.input
b.input
You can also use extractor with the help of unapply method:
val Foo(val1) = a
val Bar(val2) = b
and then use val1 and val2
Update
Then you should use pattern matching on your value:
value match {
case Foo(val1) => val1
case Bar(val1) => val1
}
It works just like val Foo(val1) = a, with using generated unapply method (extractor) in your class, and it is also an expression, so you van assign the result to the variable
If you have multiple arguments just change PatMat construct according to the number of your parameters, in your case:
someMethod(a: Something, b: Something) = (a, b) match {
case (Foo(v1), Foo(v2)) => (v1, v2) // or any other logic with values
case (Foo(v1), Bar(v2)) => // logic for this case
... // logic for other cases
}
The more parameters the more cases you should provide, but you case blank cases if you don't need them
someMethod(a: Something, b: Something) = (a, b) match {
case (Foo(v1), Foo(v2)) => (v1, v2) // or any other logic with values
case _ =>
}
in this case all other cases will be ignored, not the best choice, cause the result type will be incorrect. And you also can black values
someMethod(a: Something, b: Something) = (a, b) match {
case (Foo(v1), _) => v1 // in such case you can work only with v1
... // logic for other cases
}
An alternative to pattern matching could be do redefine your classes like this:
trait Something[T]{
def input:T
}
case class Foo(input: Int) extends Something[Int]
case class Bar(input: Double) extends Something[Double]
Then, any instance of Something will expose the input property. The only potential downside is that it will be of a generic type when you access it.
The alternative approach
In addition to the direct solution of pattern matching in your method, I'll try to show a somewhat more convoluted, general and functional approach to this kind of situations. Still pattern matching is the most direct and simple answer!
If you can explicitly "certify" in your interface the input accessor, you can generalize how you work with the Something class.
In code this translates to
trait Something[T] {
def input: T
}
case class Foo(input: Int) extends Something[Int]
case class Bar(input: Double) extends Something[Double]
from here you can define how to "lift" any function you like to one that works over Somethings
Let's say you have methods that takes two inputs (e.g. Ints or Doubles) and you want to operate on such inputs within one of your case classes (i.e. Foo, Bar)
//this function lift your specific input method to one that takes Somethings
def liftSomething2[T, R](f: (T, T) => R): (Something[T], Something[T]) => R =
(a, b) => f(a.input, b.input)
Let's examine this a bit: it takes a function
(T, T) => R of 2 arguments of type T and a result R
and transforms it in a
(Something[T], Something[T]) => R which takes Somethings as arguments.
Examples
//lifts a function that sums ints
scala> val sumInts = liftSomething2[Int, Int](_ + _)
sumInts: (Something[Int], Something[Int]) => Int = <function2>
//lifts a function that multiplies ints
scala> val multInts = liftSomething2[Int, Int](_ * _)
multInts: (Something[Int], Something[Int]) => Int = <function2>
//lifts a function that divides doubles
scala> val divDbl = liftSomething2[Double, Double](_ / _)
divDbl: (Something[Double], Something[Double]) => Double = <function2>
//Now some test
scala> sumInts(Foo(1), Foo(2))
res2: Int = 3
scala> multInts(Foo(4), Foo(-3))
res3: Int = -12
scala> divDbl(Bar(20.0), Bar(3.0))
res4: Double = 6.666666666666667
//You can even complicate things a bit
scala> val stringApp = liftSomething2[Int, String](_.toString + _)
stringApp: (Something[Int], Something[Int]) => String = <function2>
scala> stringApp(Foo(1), Foo(2))
res5: String = 12
All the above examples lift functions of type (T,T) => R but the "lifting" can be made for all and any argument you need
//This takes three args of different types and returns another type
// the logic doesn't change
def liftSomething3[A,B,C,R](f: (A,B,C) => R): (Something[A], Something[B], Something[C]) => R =
(a,b,c) => f(a.input, b.input, c.input)
//sums to ints and divides by a double
scala> val sumDiv = liftSomething3[Int,Int,Double,Double]((i,j,d) => (i + j) / d)
sumDiv: (Something[Int], Something[Int], Something[Double]) => Double = <function3>
scala> sumDiv(Foo(5), Foo(30), Bar(4.2))
res7: Double = 8.333333333333332
more...
All we've seen so far should be somewhat related to category theory concepts like Applicative Functors and Comonads, but I'm no expert so I encourage you to search for yourself if you feel this sort of abstractions are useful and interesting.
In your example both the a and b have specific types: Foo and Bar respectively. That's why you can simply access their fields like so:
scala> a.input
res4: Int = 10
scala> b.input
res5: Double = 25.1
If however your value has type Something, then you'll need to pattern-match:
val input = somethingOfTypeSomething match {
case Foo(input) => input
case Bar(input) => input
}
The other answers have covered the basic scenario. There are useful variations to consider.
Constructor Pattern
As already answered there is:
value match {
case Foo(x) => x
...
}
Deep Matching
The constructor pattern also supports deep matching. For example, extract x within Bar within Foo which is 3 levels deep:
value match {
case Foo(y, Bar(x)) => x
...
}
Variable Binding
If the value you want to extract is an actual case class inside another case class you can use variable binding. E.g. to extract the whole Bar(x) into b:
value match {
case Foo(y, b # Bar(x)) => b
...
}
Programming in Scala by M. Odersky, Spoon and Venners has a great chapter on case classes and pattern matching which covers many other scenarios. Pattern matching is such a rich part of the language it would be a worthwhile investment.
in scala play framework I seen this code:
abstract class AnalyserInfo
case class ColumnC(typeName:String,fieldName:String) extends AnalyserInfo
case class TableC(typeName:String) extends AnalyserInfo
val asIs :PartialFunction[AnalyserInfo,String] = {
case ColumnC(_,f) => f;
case TableC(typeName) => typeName
}
What is the difference with:
val asIs: (AnaliserInfo)=>String = (info) => info match {
case ColumnC(_,f) => f;
case TableC(typeName) => typeName
}
There is a preferred style? and why in the first case the match keyword can be omitted?
Thank you for the support.
Double => Double is just a shorthand for Function[Double, Double]. PartialFunction inherits from Function but adds a few methods. Most importantly, it adds the method isDefinedAt which allows you to query if the function is defined for some parameter.
The cases without a match are a special syntax to define partial functions, which generates an isDefinedAt that returns true for all matching cases.
Say we have a function that returns 1/x, but only for positive values of x, we could it define as:
scala> val f: (Double => Double) = { case x if x > 0 => 1/x }
f: (Double) => Double = <function1>
or as:
scala> val g: PartialFunction[Double, Double] = { case x if x > 0 => 1/x }
g: PartialFunction[Double,Double] = <function1>
The second version has the benefit that we could check if the function is applicable to some parameter:
scala> g.isDefinedAt(-3)
res0: Boolean = false
This feature is for example used in Scala to implement the actor library where an Actor might only consume certain types of messages.