Boolean implies another - boolean

Is there a programming language in which we can write something like:
a => b
to compute implication? (where a and b are booleans)
The closest I can find is in Scala:
a <= b
But it looks completely different from the actual meaning of "implication".

So the winner is Scala:
implicit class BooleanMagic(val b: Boolean) extends AnyVal {
def ==>(other: =>Boolean) = !b || other
}
Thanks to that:
> true ==> false
res0: Boolean = false
> false ==> (throw new Exception("I'm the president"))
res1: Boolean = true

Related

Scala filter on all elements of an alias Set

Here is the question.
I have this type Set:
type Set = Int => Boolean
Which i can use like this:
val belowNegFive: Set = (i) => i < -5
belowNegFive(10)
I mean to return a bool depending if the elem 10 pertains to the set of numbers below -5.
I have this code, which returns the subset of s for which p holds.
def filter(s: Set, p: Int => Boolean): Set = (e: Int) => s(e) && p(e)
Q1: How do I know p(e) tells me that the int e satisfies the predicate p?
I have this fc, which returns whether all bounded integers within s satisfy p.
def contains(s: Set, elem: Int): Boolean = s(elem)
val bound = 1000
def forall(s: Set, p: Int => Boolean): Boolean = {
def iter(a: Int): Boolean = {
if (a > bound) true
else if (contains(s, a) && !p(a)) false
else iter(a+1)
}
iter(-bound)
}
Q2: Why do all a > bound simply satisfy the condition of the predicate by default? Or true is just a stop condition? I am not sure why this fc does not return an infinite loop. Just an infinite list of Booleans, and the last Booleans are "true, true, true ..." for all a > bound.
Q3: And i do not see in which point it uses && between resulting Booleans in order to say yes, all bounded integers within s satisfy p.
thank you
For Q1:
p is a function which takes an integer and returns a boolean. My predicate can be something like, the number should be less than -10. My set can be, it should be less than -5. filter will return that custom set for which both hold.
type Set = Int => Boolean
val belowNegFive: Set = (i) => i < -5
def filter(s: Set, p: Int => Boolean): Set = (e: Int) => s(e) && p(e)
val predicate: Int => Boolean = (num) => num < -10
val myset = filter(belowNegFive, predicate)
myset(0) #=> false
myset(-1) #=> false
myset(-10) #=> false
myset(-11) #=> true
For Q2:
def contains(s: Set, elem: Int): Boolean = s(elem)
val bound = 1000
def forall(s: Set, p: Int => Boolean): Boolean = {
def iter(a: Int): Boolean = {
if (a > bound) true
else if (contains(s, a) && !p(a)) false
else iter(a+1)
}
iter(-bound)
}
It's a stop condition. forall dictates that if for all integers b/w -1000 to 1000 (bound), if set contains the integer and predicate holds, it is true. AS you can see, in last line, the check is started from -1000 (iter(-bound)).
Q3: what will truth table for set and predicate look like?
set | predicate | should continue checking?
____________________________________________
true | true | yes
false| true | yes
true | false | no
false| false | yes
As you can see, only condition it should return false is the third one, which is the else if condition. For all others, it continues to check with the next integer for presence in set and predicate.

Scala: How to override tuple equals() method for arbitrary element types?

I have a map with values keyed by tuple. In my case I need tuples match irrespective of elements order so, for example, I need this to hold:
(1, 2) == (2, 1) is true
How to override tuple equals operator, so for any types X, Y :
(a:X, b:Y) == (b:Y, a:X) is true ?
Corrected later: Another idea would be to write my own Pair class with required behavior. How equals() override will look like in this case?
Of course you don't really want to change the semantics of tuples, because the universe would implode. You just want something like tuples -- except for their equality semantics.
Why not just use a case class? Tuples are really just ready-made classes to hold a few things together when it isn't worth the trouble to define a class. Well, if you want to change equality, I'd say it's worth the trouble! Plus you can use more meaningful names than _1 and _2.
I don't know what those names would be, of course, but here's some code. As Travis points out, messing with equality is tricky, in part because you also have to think about the hash code. Hopefully this is reasonable:
scala> case class Foo[T]( a:T, b:T ) {
override def equals( that:Any ) = that match {
case that:Foo[T] => ( that canEqual this ) && (
this.a == that.a && this.b == that.b ||
this.a == that.b && this.b == that.a
)
case _ => false
}
override def canEqual( that:Any ) = that.isInstanceOf[Foo[T]]
override def hashCode = a.hashCode + b.hashCode
}
defined class Foo
scala> Foo(1,2) == Foo(1,2)
res15: Boolean = true
scala> Foo(1,2) == Foo(2,1)
res16: Boolean = true
scala> Foo(1,2) == Foo(2,2)
res17: Boolean = false
scala> collection.immutable.HashSet( Foo(0,1), Foo(1,0), Foo(1,2) )
res18: scala.collection.immutable.HashSet[Foo[Int]] = Set(Foo(0,1), Foo(1,2))
Note that res18 contains Foo(1,0) but not Foo(0,1) because of that definition of equality.
Well, you can't override the behavior defined for Tuple2. After all, those two tuples are not equal, so you can't tell scala to say that they are.
You could define your own kind of tuple that has the equality property you want, but then you wouldn't be able to use the nice parentheses syntax.
The easiest way is to just define your own equality function that you call:
def myEquals[X,Y](a: (X,Y), b: (Y,X)) = a._1 == b._2 && a._2 == b._1
So then you have:
scala> myEquals((1,'a'), ('a',1))
res0: Boolean = true
You could also define a new equality operator for Tuple2
implicit class NewEqualityTuple2[X,Y](a: (X,Y)) {
def =<>=(b: (Y,X)) = a._1 == b._2 && a._2 == b._1
}
Giving this:
scala> (1,'a') =<>= ('a',1)
res1: Boolean = true

Union of two sets in Scala

From the question linked here, I found this implementation of Union in Scala:
def union(a: Set, b: Set): Set = i => a(i) || b(i)
And Set is a function of type:
type Set = Int => Boolean
Now I understand that in Scala, a function is mapped from Int to Boolean here, and I further understand how this statement is executed:
a(i) || b(i)
But what I don't understand is what is 'i' here. Where does it come from? And when it finds a match between to sets, it returns true, if it indeed does, where do I filter it?
The Set (which is just a function) that gets returned from union takes some integer as a parameter; you must give it an arbitrary name so that you can refer to it in the function body. It may make more sense if you write the function like this:
def union(a: Set, b: Set): Set = {
(i) => a(i) || b(i)
}
It may make even more sense if you write it like this:
def union(a: Set, b: Set): Set = {
// The union of two sets is a new function that takes an Int...
def theUnion(i: Int): Boolean = {
// and returns true if EITEHR of the other functions are true
a(i) || b(i)
}
// Now we want to return the NEW function
theUnion
}
Again, i is arbitrary and could be replaced with any variable:
def union(a: Set, b: Set): Set = item => a(item) || b(item)
[Update]
Because we're representing sets as functions, there's no need to iterate to see if they contain a number. For example, here's a set that contains any number below -5:
val belowNegFive: Set = (i) => i < -5
When we call that function with a number, it will tell us if that number is in the set. Note that at no time did we actually tell it the specific numbers that were in the set:
scala> belowNegFive(10)
res0: Boolean = false
scala> belowNegFive(-100)
res1: Boolean = true
scala> belowNegFive(-1)
res2: Boolean = false
Here's another set that includes any number between 50 and 100:
val fiftyToHundred: Set = (i) => i >= 50 && i <= 100
scala> fiftyToHundred(50)
res3: Boolean = true
scala> fiftyToHundred(100)
res4: Boolean = true
scala> fiftyToHundred(75)
res5: Boolean = true
scala> fiftyToHundred(49)
res6: Boolean = false
Now, a union of the sets belowNegFive and fiftyToHundred would contain any number that is either below -5 or between 50 and 100. We can easily represent this in code by returning a new function which itself returns true if either of the other two functions returns true.
scala> val unionOfBoth: Set = (i) => belowNegFive(i) || fiftyToHundred(i)
unionOfBoth: Int => Boolean = <function1>
scala> unionOfBoth(-10)
res7: Boolean = true
scala> unionOfBoth(50)
res8: Boolean = true
scala> unionOfBoth(0)
res9: Boolean = false
The union function from your question is just a way of applying this pattern generically over any two sets.
Let say we have object called SoSet given by
object SoSet {
type Set = Int => Boolean
val a : Set = ???
val b : Set = ???
def isItem(item : Int) = a(item) || b(item)
}
The signature of isItem is given by Int => Boolean which is a Set. So far so good.
But now we just want to return the function isItem (i.e. a Set).
So lets define union function for this (There are no parameters right now. We will add it later).
object SoSet {
//..
def union : Set = isItem // returns the function isItem
}
Now lets refactor the isItem into a anonymous function.
object SoSet {
//..
def union : Set = {
(item : Int) => a(item) || b(item)
}
}
Lets move Set a and b from object SoSet to parameters of def union. Refactor item to i.
object SoSet {
type Set = Int => Boolean
def union(a : Set, b : Set) : Set = (i : Int) => a(i) || b(i)
}
UPDATE
val s1 = Set(1, 2, 3)
val s2 = Set(2, 3, 4)
val s3 = union(s1, s2) // returns the function.. Int => Boolean = <function1>
s3(2) // invokes the function & checks if 2 is present in the union
And when it finds a match between to sets, it returns true, if it indeed does, where do I filter it?
union does not find a match between two sets, it creates a new set which contains the values of
both sets. Example:
val a = (i) => i == 2 // a contains 2 as a(2) == True
val b = (i) => i == 5 // b contains 5 as b(5) == True
val u = union(a, b) // u contains 2 and 5 as u(2) == True and u(5) == True
So the 'filtering' just happens on the way. This function is not iterating over each set, filtering specific things out, it just returns a combination of two functions which then can executed later to query for the actual values.
Example of querying the values of a union:
val a = (i) => i == 2
val b = (i) => i == 5
val u = union(a, b)
for(i <- 1 to 10 if u(i)) yield i // returns Vector(2, 5)
And yes, this is not an optimal way of storing values in sets as you have to check values by
guessing but it is a good way to demonstrate how combining functions adds complex functionality without
writing very complex code.
You can implement a union function like this:
def union[A](set1: Set[A], set2:Set[A]):Set[A] = {
set1.foldLeft(set2)((set, elem) => set + elem)
}
or
def union[A](set1: Set[A], set2:Set[A]):Set[A] = {
set1.flatMap(elem => set2 + elem)
}
These will be generic so you can use it for sets of any type

Idiomatic construction to check whether a collection is ordered

With the intention of learning and further to this question, I've remained curious of the idiomatic alternatives to explicit recursion for an algorithm that checks whether a list (or collection) is ordered. (I'm keeping things simple here by using an operator to compare and Int as type; I'd like to look at the algorithm before delving into the generics of it)
The basic recursive version would be (by #Luigi Plinge):
def isOrdered(l:List[Int]): Boolean = l match {
case Nil => true
case x :: Nil => true
case x :: xs => x <= xs.head && isOrdered(xs)
}
A poor performing idiomatic way would be:
def isOrdered(l: List[Int]) = l == l.sorted
An alternative algorithm using fold:
def isOrdered(l: List[Int]) =
l.foldLeft((true, None:Option[Int]))((x,y) =>
(x._1 && x._2.map(_ <= y).getOrElse(true), Some(y)))._1
It has the drawback that it will compare for all n elements of the list even if it could stop earlier after finding the first out-of-order element. Is there a way to "stop" fold and therefore making this a better solution?
Any other (elegant) alternatives?
This will exit after the first element that is out of order. It should thus perform well, but I haven't tested that. It's also a lot more elegant in my opinion. :)
def sorted(l:List[Int]) = l.view.zip(l.tail).forall(x => x._1 <= x._2)
By "idiomatic", I assume you're talking about McBride and Paterson's "Idioms" in their paper Applicative Programming With Effects. :o)
Here's how you would use their idioms to check if a collection is ordered:
import scalaz._
import Scalaz._
case class Lte[A](v: A, b: Boolean)
implicit def lteSemigroup[A:Order] = new Semigroup[Lte[A]] {
def append(a1: Lte[A], a2: => Lte[A]) = {
lazy val b = a1.v lte a2.v
Lte(if (!a1.b || b) a1.v else a2.v, a1.b && b && a2.b)
}
}
def isOrdered[T[_]:Traverse, A:Order](ta: T[A]) =
ta.foldMapDefault(x => some(Lte(x, true))).fold(_.b, true)
Here's how this works:
Any data structure T[A] where there exists an implementation of Traverse[T], can be traversed with an Applicative functor, or "idiom", or "strong lax monoidal functor". It just so happens that every Monoid induces such an idiom for free (see section 4 of the paper).
A monoid is just an associative binary operation over some type, and an identity element for that operation. I'm defining a Semigroup[Lte[A]] (a semigroup is the same as a monoid, except without the identity element) whose associative operation tracks the lesser of two values and whether the left value is less than the right value. And of course Option[Lte[A]] is just the monoid generated freely by our semigroup.
Finally, foldMapDefault traverses the collection type T in the idiom induced by the monoid. The result b will contain true if each value was less than all the following ones (meaning the collection was ordered), or None if the T had no elements. Since an empty T is sorted by convention, we pass true as the second argument to the final fold of the Option.
As a bonus, this works for all traversable collections. A demo:
scala> val b = isOrdered(List(1,3,5,7,123))
b: Boolean = true
scala> val b = isOrdered(Seq(5,7,2,3,6))
b: Boolean = false
scala> val b = isOrdered(Map((2 -> 22, 33 -> 3)))
b: Boolean = true
scala> val b = isOrdered(some("hello"))
b: Boolean = true
A test:
import org.scalacheck._
scala> val p = forAll((xs: List[Int]) => (xs /== xs.sorted) ==> !isOrdered(xs))
p:org.scalacheck.Prop = Prop
scala> val q = forAll((xs: List[Int]) => isOrdered(xs.sorted))
q: org.scalacheck.Prop = Prop
scala> p && q check
+ OK, passed 100 tests.
And that's how you do idiomatic traversal to detect if a collection is ordered.
I'm going with this, which is pretty similar to Kim Stebel's, as a matter of fact.
def isOrdered(list: List[Int]): Boolean = (
list
sliding 2
map {
case List(a, b) => () => a < b
}
forall (_())
)
In case you missed missingfaktor's elegant solution in the comments above:
Scala < 2.13.0
(l, l.tail).zipped.forall(_ <= _)
Scala 2.13.x+
l.lazyZip(l.tail).forall(_ <= _)
This solution is very readable and will exit on the first out-of-order element.
The recursive version is fine, but limited to List (with limited changes, it would work well on LinearSeq).
If it was implemented in the standard library (would make sense) it would probably be done in IterableLike and have a completely imperative implementation (see for instance method find)
You can interrupt the foldLeft with a return (in which case you need only the previous element and not boolean all along)
import Ordering.Implicits._
def isOrdered[A: Ordering](seq: Seq[A]): Boolean = {
if (!seq.isEmpty)
seq.tail.foldLeft(seq.head){(previous, current) =>
if (previous > current) return false; current
}
true
}
but I don't see how it is any better or even idiomatic than an imperative implementation. I'm not sure I would not call it imperative actually.
Another solution could be
def isOrdered[A: Ordering](seq: Seq[A]): Boolean =
! seq.sliding(2).exists{s => s.length == 2 && s(0) > s(1)}
Rather concise, and maybe that could be called idiomatic, I'm not sure. But I think it is not too clear. Moreover, all of those methods would probably perform much worse than the imperative or tail recursive version, and I do not think they have any added clarity that would buy that.
Also you should have a look at this question.
To stop iteration, you can use Iteratee:
import scalaz._
import Scalaz._
import IterV._
import math.Ordering
import Ordering.Implicits._
implicit val ListEnumerator = new Enumerator[List] {
def apply[E, A](e: List[E], i: IterV[E, A]): IterV[E, A] = e match {
case List() => i
case x :: xs => i.fold(done = (_, _) => i,
cont = k => apply(xs, k(El(x))))
}
}
def sorted[E: Ordering] : IterV[E, Boolean] = {
def step(is: Boolean, e: E)(s: Input[E]): IterV[E, Boolean] =
s(el = e2 => if (is && e < e2)
Cont(step(is, e2))
else
Done(false, EOF[E]),
empty = Cont(step(is, e)),
eof = Done(is, EOF[E]))
def first(s: Input[E]): IterV[E, Boolean] =
s(el = e1 => Cont(step(true, e1)),
empty = Cont(first),
eof = Done(true, EOF[E]))
Cont(first)
}
scala> val s = sorted[Int]
s: scalaz.IterV[Int,Boolean] = scalaz.IterV$Cont$$anon$2#5e9132b3
scala> s(List(1,2,3)).run
res11: Boolean = true
scala> s(List(1,2,3,0)).run
res12: Boolean = false
If you split the List into two parts, and check whether the last of the first part is lower than the first of the second part. If so, you could check in parallel for both parts. Here the schematic idea, first without parallel:
def isOrdered (l: List [Int]): Boolean = l.size/2 match {
case 0 => true
case m => {
val low = l.take (m)
val high = l.drop (m)
low.last <= high.head && isOrdered (low) && isOrdered (high)
}
}
And now with parallel, and using splitAt instead of take/drop:
def isOrdered (l: List[Int]): Boolean = l.size/2 match {
case 0 => true
case m => {
val (low, high) = l.splitAt (m)
low.last <= high.head && ! List (low, high).par.exists (x => isOrdered (x) == false)
}
}
def isSorted[A <: Ordered[A]](sequence: List[A]): Boolean = {
sequence match {
case Nil => true
case x::Nil => true
case x::y::rest => (x < y) && isSorted(y::rest)
}
}
Explain how it works.
my solution combine with missingfaktor's solution and Ordering
def isSorted[T](l: Seq[T])(implicit ord: Ordering[T]) = (l, l.tail).zipped.forall(ord.lt(_, _))
and you can use your own comparison method. E.g.
isSorted(dataList)(Ordering.by[Post, Date](_.lastUpdateTime))

How to define a ternary operator in Scala which preserves leading tokens?

I'm writing a code generator which produces Scala output.
I need to emulate a ternary operator in such a way that the tokens leading up to '?' remain intact.
e.g. convert the expression c ? p : q to c something. The simple if(c) p else q fails my criteria, as it requires putting if( before c.
My first attempt (still using c/p/q as above) is
c match { case(true) => p; case _ => q }
another option I found was:
class ternary(val g: Boolean => Any) { def |: (b:Boolean) = g(b) }
implicit def autoTernary (g: Boolean => Any): ternary = new ternary(g)
which allows me to write:
c |: { b: Boolean => if(b) p else q }
I like the overall look of the second option, but is there a way to make it less verbose?
Thanks
Even though the syntax doesn't evaluate in the expected order--it binds the conditional to the first option!--you can make your own ternary operator like this:
class IfTrue[A](b: => Boolean, t: => A) { def |(f: => A) = if (b) t else f }
class MakeIfTrue(b: => Boolean) { def ?[A](t: => A) = new IfTrue[A](b,t) }
implicit def autoMakeIfTrue(b: => Boolean) = new MakeIfTrue(b)
The trick is to interpret ? as a method on a MakeIfTrue object that binds the condition to the object to return in the "true" case. The resulting IfTrue object now uses the | method as a request to evaluate the condition, returning the stored true option if the condition is true, or the just-passed-in one if it's false.
Note that I've used stuff like => A instead of just A--by-name parameters--in order to not evaluate the expression unless it's actually used. Thus, you'll only evaluate the side that you actually need (just like an if statement).
Let's see it in action:
scala> List(1,3,2).isEmpty ? "Empty" | "Nonempty"
res0: java.lang.String = Nonempty
scala> (4*4 > 14) ? true | false
res1: Boolean = true
scala> class Scream(s: String) { println(s.toUpperCase + "!!!!") }
defined class Scream
scala> true ? new Scream("true") | new Scream("false")
TRUE!!!!
res3: Scream = Scream#1ccbdf7
(P.S. To avoid confusion with the Actor library ?, you probably ought to call it something else like |?.)
Let's keep it simple:
Java:
tmp = (a > b) ? a : b;
Scala:
tmp = if (a > b) a else b
Besides simplicity, it is clear and fast because: do not allocate objects you don't need, keeps the garbage collector out of equation (as it always should be) and makes better use of processor caches.
You could use something like this
sealed trait TernaryOperand[A] {
def >(q: => A): A
}
case class TernarySecond[A](val p: A) extends TernaryOperand[A] {
def >(q: => A) = p
}
case class TernaryThird[A]() extends TernaryOperand[A] {
def >(q: => A) = q
}
implicit def ternary(c: Boolean) = new {
def ?[A](p: => A): TernaryOperand[A] = if (c) TernarySecond(p) else TernaryThird()
}
val s1 = true ? "a" > "b"
println(s1) //will print "a"
val s2 = false ? "a" > "b"
println(s2) //will print "b"
This code converts any boolean value to an anonymous type that has a method called ?. Depending on the value of the boolean, this method will either return TernarySecond or TernaryThird. They both have a method called > which returns the second operand or the third one respectively.
Ternary operator which adds my improvement to the best of Rex Kerr’s and Michel Krämer’s implementations:
My improvement to use Scala’s new value class to avoid boxing overhead.
Call by-name on 2nd and 3rd operands so only the chosen one is evaluated.
Michel’s call by-value on the 1st (Boolean) operand to avoid by-name overhead; it is always evaluated.
Rex’s concrete class for the condition to avoid any anonymous class overhead.
Michel’s evaluation of the condition to determine which class to construct to avoid of overhead of a two argument constructor.
.
sealed trait TernaryResult[T] extends Any {
def |(op3: => T): T
}
class Ternary2ndOperand[T](val op2: T) extends AnyVal with TernaryResult[T] {
def |(op3: => T) = op2
}
class Ternary3rdOperand[T](val op2: T) extends AnyVal with TernaryResult[T] {
def |(op3: => T) = op3
}
class Ternary(val op1:Boolean) extends AnyVal {
def ?[A](op2: => A): TernaryResult[A] = if (op1) new Ternary2ndOperand(op2) else new Ternary3rdOperand(op2)
}
object Ternary {
implicit def toTernary(condition: Boolean) = new Ternary(condition)
}
Note the improvement over if else is not just the 6 characters saved. With Scala IDE’s syntax coloring on keywords being the same (e.g. purple) for if, else, null, and true, there is better contrast in some cases (which isn't shown by the syntax coloring below as currently rendered on this site):
if (cond) true else null
cond ? true | null