So suppose I have a function that expects a Set with definition Int => Boolean and a function f like this:
def map(s: Set, f: Int => Int): Set = {}
Now how do I apply this f to each element of this set s.
def map(s: Set, f: Int => Int): Set = { (i: Int) => f(s(i)) }
Which is ofcourse incorrect because in f(s(i)), 's(i)' returns a boolean, and thus can't apply f on it. Problem is how do I access each element of Set and apply this f on it?
This question is part of Coursera's Functional Programming with Scala course.
A goal of the course is to help you understand the functional model, and in this case, how the Set can be represented by a function (called the charasteristic function for that set).
Instead of the final solution, here's a hint on how to reason about this problem:
Given the characteristic function f: Int => Boolean that defines your set and x, an Int, if f(x) == true, then x belongs to the Set. Now, if you have a function g:Int=>Int
that you want to map over the set, what you want is to apply that function to the elements that you know that belong to the set: if (f(x)) then g(x).
Try to apply that thinking to your exercise.
If you wrote the exists function correctly:
def map(s: Set, f: Int => Int): Set = (i: Int) => exists(s, (x: Int) => i == f(x))
Bam one line!
You need to use fold to do this.
def map(s: Set[Int], f: Int => Int): Set[Int] =
s.foldLeft(Set.empty[Int])((s,i) => s+f(i))
Related
It's a question regarding syntactic sugars in Scala functions, similar discussion could be found here and here. Both answers give great insights, but I still cannot get my head aroud.
That is, I could not understand how characteristic function works?
Characteristic function (see the code below):
s(elem)
Set(elem)
Let's see an example,
object devScript extends App {
type Set = Int => Boolean
def contains(s: Set, elem: Int): Boolean = s(elem)
def singletonSet1(elem: Int): Set = (x: Int) => x == elem
def singletonSet2(elem: Int): Set = Set(elem)
println(contains(singletonSet1(5), 5))
println(contains(singletonSet2(5), 5))
}
Returns:
true
true
singletonSet1 and singletonSet2 have given the same result, so are they just two functions that expressing the same thing but in different forms? Moreover, without explicitly define a Boolean clause, how could a function return true/false?
I think this example is a bit confusing because there are two definitions of Set in scope. You define your own type alias Set which has a type of a function that takes Int and returns Boolean: Int => Boolean. On the other hand you also have Set from Scala collections in scope which has apply function which is also of the same type: Int => Boolean. Let's look at these types in REPL:
scala> singletonSet1 _
res1: Int => Set = $$Lambda$1261/1618596377#4ed90b04
scala> singletonSet2 _
res2: Int => Set = $$Lambda$1262/224661478#14f08a97
scala> Set(1).apply _
res3: Int => Boolean = $$Lambda$1352/273821181#17d6b6e
// same as apply above
scala> Set(1)(_)
res4: Int => Boolean = $$Lambda$1377/1981148063#4ebe0e3f
scala> singletonSet1(1)
res5: Set = $$Lambda$1230/593573468#7574d30b
scala> singletonSet1(1)(1)
res6: Boolean = true
// or similarly:
scala> singletonSet2(1)(1)
res7: Boolean = true
As you can see apply, also written as () conforms to the type that you need to return from your singletonSet[1|2] function.
You are right that both of them can be used as functions which are implemented in different forms: using closures for singletonSet1 and using regular Scala Set in singletonSet2 case.
Note that singletonSet[1|2] doesn't return boolean, it returns a function that will return a Boolean provided you've given it an Int. There is one more level of indirection involved. If you write out the type of these functions entirely it will look like this: Int => Int => Boolean, or equivalently: Int => Set.
Coincidentally I wrote a blog post trying to explain how this works. You can check it out here:http://izmailoff.github.io/programming%20languages/functional%20programming/functional_sets. Hopefully it's clear enough.
The Set(elem) refers to the companion object of scala.collection.Set, which is a value, and therefore is not shadowed by your type-definition Set.
Just run this to see it:
object devScript extends App {
type Set = Int => Boolean
def contains(s: Set, elem: Int): Boolean = s(elem)
def singletonSet1(elem: Int): Set = (x: Int) => x == elem
def singletonSet2(elem: Int): Set = Set(elem)
println(contains(singletonSet1(5), 5))
println(contains(singletonSet2(5), 5))
println(singletonSet2(42).getClass)
}
It will print true, true, class scala.collection.immutable.Set$Set1,
instead of something like Int => Boolean, as you might have expected.
Even more confusingly, the contains(singletoSet2(5), 5) also works, because, scala's standard collection Set[A] also implements A => Boolean, as can be seen in the documentation.
It's probably obvious, but it's making me crazy and I think my code is being bloated as a result (missing the obvious, not the making me crazy part).
I have a method as follows:
def fun(f: Int => Boolean, y: Int): Int
This method is going to be called like this fun(*some anon func*, y) and should increase and return y + 1 when some anon function (applied to some param) is greater than 0 and y - 1 otherwise. How to define fun? I'm trying something like
def fun(f: Int => Boolean, y: Int): Int =
if (f) y - 1
else y + 1
Obviously, that doesn't work. I should put f(tmp), where tmp:Int but I'm now sure how to express that.
All examples I could find online always apply f on y, but this is just funny.
Update: here's a similar problem I have already solved, but am not happy with how did I do it:
For a given function forall(s: Set, p: Int => Boolean): Boolean, which returns true iff all the set elements x in S (def S: int => Boolean, indicator function for set S) satisfy p(x), create a function that will implement exists quantifier (exists function). In set theory, one can express this quantifier as (in terms of the problem described above) not all elements (not forall) of a set satisfy NOT p.
I did something like this:
def exists(s: Set, p: Int => Boolean): Boolean = {
def negP(x: Int): Boolean = !p(x)
!forall(s, negP)
}
My question is: how to do this without defining negP? I cannot state !p because Scala gives error for ! operator. I cannot use !p(x) because there is no x. Hence the problem above and my question.
TIA
You could make it return a function that does that, like so:
def fun(f: Int => Int, y: Int): Int => Int =
input => if (f(input) > 0) y - 1 else y + 1
val test1 = fun(x => x*2, 1)
println(test1(-1)) // "2"
val test2 = fun(x => x - 100, 5)
println(test2(101)) // "4"
val test3 = fun(x => x, -10)
println(test3(0)) // "-9"
EDIT: Note that I changed the signature of the input function, as I think it probably reflects the requirements better, changing it back to boolean should be trivial(see other answers). :)
EDIT(2):
Seeing is you updated your question, I thought best to update my answer: You can always just inline a function, in your example, maybe you could do it like this:
def exists(s: Set, p: Int => Boolean): Boolean = !forall(s, x => !p(x))
Your original problem can't be solved because you can't test the output of f() without invoking f(), and you can't invoke f() without an input argument to pass. I think the best you can hope for is something like this.
def fun(f: Int => Boolean, y: Int): Int => Int = (arg: Int) =>
if (f(arg)) y - 1
else y + 1
Your "similar problem" looks to me like it should be a different question.
Your proposed solution can be solved via recursion, but using forall() it can be expressed more concisely.
def exists(s: Set[Int], p: Int => Boolean): Boolean =
!forall(s, (x:Int) => !p(x))
It sounds like you don't actually want to pass a parameter to your anonymous function? Then try this:
def fun(f: () => Boolean, y: Int): Int =
if (f()) y - 1
else y + 1
I have two functions. One is masterChecker, wich takes as argument an Int x and a function p, and return the boolean result p(x). Simple like that.
def masterChecker(x: Int, p: Int => Boolean): Boolean = p(x)
Then I have a second function childChecker, which is like an alias to masterChecker
def childChecker(x: Int, f: Int => Boolean): Boolean = masterChecker(x , f)
Is there any way to change f in the masterCheker call on childChecker, in a manner that it would run like !f ? (if f return true, than make it false)
Like:
// inside childChecker
masterChecker(x, !f)
I know that I could do it on the masterChecker call with !masterChecker(x,f), but what I want to know is if it´s possible to change a function behavior passed as an argument.
Sure, you can use an anonymous function like so:
def childChecker(x: Int, f: Int => Boolean) = masterCheck(x, !f(_))
and there you go!
Even more so, you could do a number of things if you want to "modify" f within the function scope of childChecker:
def childChecker(x: Int, f: Int => Boolean) ={
def proxy(x: Int): Boolean ={
val y: Int = //do things
f(y) //see? "y" not "x"
}
masterCheck(x, proxy)
}
that's part of the fun when you're dealing with plain ol' functions. Granted, this "modification" is more of a decorator pattern but it does adhere to the interface.
I have two functions which accept a function type: Int => Boolean function type
def myFunction1(f1: Int => Boolean) ...
def myFunction2(f2: Int => Boolean) ...
I want to call function2 from function1 but instead of just invoking it with f1, I want to invoke it with the inverse of f1. So if f1 is something like
(x: Int) => x > 4
at runtime, i.e. return true for numbers greater than four. I want the reverse returns false if numbers are greater than four. Is it possible to inverse f1 before calling myFunction2?
You could do something like this:
def myFunction1(f1: Int => Boolean) = myFunction2(!f1(_))
def myFunction1(f1: Int => Boolean) = myFunction2(f1 andThen (! _))
I'm trying to understand the advantages of currying over partial applications in Scala. Please consider the following code:
def sum(f: Int => Int) = (a: Int, b: Int) => f(a) + f(b)
def sum2(f: Int => Int, a: Int, b: Int): Int = f(a) + f(b)
def sum3(f: Int => Int)(a: Int, b: Int): Int = f(a) + f(b)
val ho = sum({identity})
val partial = sum2({ identity }, _, _)
val currying = sum3({ identity })
val a = currying(2, 2)
val b = partial(2, 2)
val c = ho(2, 2)
So, if I can calculate partially applied function that easy, what are the advantages of currying?
Currying is mostly used if the second parameter section is a function or a by name parameter. This has two advantages. First, the function argument can then look like a code block enclosed in braces. E.g.
using(new File(name)) { f =>
...
}
This reads better than the uncurried alternative:
using(new File(name), f => {
...
})
Second, and more importantly, type inference can usually figure out the function's parameter type, so it does not have to be given at the call site.
For instance, if I define a max function over lists like this:
def max[T](xs: List[T])(compare: (T, T) => Boolean)
I can call it like this:
max(List(1, -3, 43, 0)) ((x, y) => x < y)
or even shorter:
max(List(1, -3, 43, 0)) (_ < _)
If I defined max as an uncurried function, this would not work, I'd have to call it like this:
max(List(1, -3, 43, 0), (x: Int, y: Int) => x < y)
If the last parameter is not a function or by-name parameter, I would not advise currying. Scala's _ notatation is amost as lightweight, more flexible, and IMO clearer.
I think it becomes clearer if you invert your curried example:
def sum4(a: Int, b: Int)(f: Int => Int): Int = f(a) + f(b)
val d = sum4(2, 2) { x =>
x * x
}
It is more of an optical effect but you don’t need to use any parentheses around the whole expression. Of course you can achieve the same result using partial application or by creating a helper method to invert the arguments, sure. The point is, that you don’t have to do all of this if you start with a curried method in the first place. In that sense currying is more of an API and syntax sugar thing. It is not expected that you use
val partial_sum4 = sum4(2, 2)
anywhere in your code or that this is in any way especially meaningful to do. It is just that you get a nicely looking expression easily.
(Well, and there are some advantages with respect to type inference…)