Scala has direct support for using hex and octal numbers:
scala> 01267 + 0100
res1: Int = 759
scala> 0x12AF + 0x100
res2: Int = 5039
but how do you do express an integer as a binary number in Scala ?.
If performance is not an issue, you can use a String and convert it to an integer.
val x = Integer.parseInt("01010101", 2)
Binary numbers aren't supported directly in part because you can easily convert from hexadecimal to binary and vice versa. To make your code clearer, you can put the binary number in a comment.
val x = 0x55 //01010101
In 2.10 you can create a string interpolator for that, e.g. it's possible to write b"0010" to mean 2. Using macros you can get rid of associated runtime overhead and do the conversion at compile-time. Take a look at Jason Zaugg's macrocosm to see it in action:
scala> b"101010"
res4: Int = 42
scala> b"102"
<console>:11: error: exception during macro expansion: invalid binary literal
b"102"
^
Using the new "implicit class" and "value class" mechanisms in 2.10, you can write something like this to add convenience methods without the overhead of object creation:
implicit class IntToBase( val digits:String ) extends AnyVal {
def base(b:Int) = Integer.parseInt( digits, b )
def b = base(2)
def o = base(8)
def x = base(16)
}
That allows you to do things like
"555".o // 365 decimal
and no IntToBase object is ever actually created.
You would need to be careful if you're converting from an integer that "looks like" binary as #agilesteel suggests. For example 0101.b would try to convert 65 decimal to binary (initial 0 signifying octal), whereas 101.b would try to convert 101 decimal to binary. It only really makes sense to try to convert from a String, for which there is Integer.parseInt, and from a number to the binary String representation, for which there is Integer.toString(x, 2).
I can't think of too many use-cases for programmatic binary literals. That said, they've made it to Java 7 as a number with prefix 0b, so I'd be surprised if they didn't appear in Scala soon. Java seems to have done fine without them for 15 years though.
If you are planning on using it a lot you can simulate the behavior with an implicit conversion.
object Extensions {
implicit def conversion(x: Int) = new BinaryInt(x)
class BinaryInt(x: Int) {
def b = {
// Conversion code like Integer.parseInt
// as Kim suggested
}
}
}
Now you can do stuff like
import Extensions._
val x = 0101.b
// or
val x = 5.b
You have to decide for yourself, which direction the conversion should go.
If you want to get a string of the binary representation of an Int you can call 4.toBinaryString. Padding is more difficult. You'll have to do something like: 4.toBinaryString.reverse.padTo(8, "0").reverse.mkString
def _0b(row: Int): Int = {
row.toString
.reverse
.split("")
.zipWithIndex
.map(x => (x._1.toInt, x._2))
.filter(_._1 == 1)
.map(x => Math.pow(2,x._2).toInt)
.sum
}
_0b(10011001) = 153
Though it is limited to 32Bit Values
Related
I'm trying to convert a generic string to a number using scala
object h extends App {
def castTo[T](s: String): T = {
s.asInstanceOf[T]
}
print(castTo[Int]("20"))
print(castTo[Double]("20.1"))
}
the data:
name | value
a | "1"
b | "2.123"
c | "abd"
the usecase:
riight now I'm exporting the data to the user a method for each conversion.
getNameAsDouble, getNameAsInteger and so forth.
I wish to do getNameT to save lot's of code and make it a bit more pretty and easy to read the doc.
so, in case a programmer does :
getNameInt i want the program to print in this case: 1
getNameDouble i want the program to print in this case: 2.123
in cpp i could use dynamic_cast. there a way to do so in scala?
( i also tried to do so in java but couldn't find a way)
p.s.
i've tried something like this, but i wandered if there is more generic way.
castTo[T] (s:String): T = {
...
case T instance of Integer => s.toInt
case T instance of Long => s.toLong
...
}
I believe it would be better if you can expand more on your use case.
But, this should do what you want.
def readAs[T](str: String)(implicit num: Numeric[T]): Option[T] =
num.parseString(str)
Which you can test like:
readAs[Int]("10")
// res: Option[Int] = Some(10)
readAs[Double]("10")
// res: Option[Double] = Some(10.0)
readAs[Double]("10.0d")
// res: Option[Double] = Some(10.0)
readAs[Int]("10.0d")
// res: Option[Int] = None
readAs[Int]("blah")
// res: Option[Int] = None
Scala is not javascript. Scala is a real programming language with types. Strong types even. So, it treats conversions between types as what they really are: conversions. Not "casts". So, the string will have to be parsed into a number. And if you wrap this parsing in a function, it is utterly wrong to call this conversion a "cast".
And no, you cannot cast a string to a number in C++ either. Not with a dynamic cast, nor with any other kind of cast. You also have to parse it in C++, because C++ is also a real programming language.
As for simplifying your pattern matching expression, you might be able to first parse the string into a double, and then use a generic cast to convert that double into a number of lesser precision, but I do not have a Scala compiler at hand to prove the concept.
Apparently scala does not support the jdk7 and later underscores in numeric literals?
I am using jdk 8
scala> System.getProperty("java.version")
res0: String = 1.8.0_40
Here we try to use a jdk7 (and later) numeric literal:
scala> val x = 1_000_000
<console>:1: error: Invalid literal number
val x = 1_000_000
^
Is there a scala language option for this?
In the Scala land you may have seen things like:
s"My name is $firstName"
and
sql"select id, name from members where id = ${id}"
There's no reason not to have:
i"1 000 000"
or even:
animal"Dog" // checks that Dog is on the list of animal words
There is no i string interpolation built in to the Scala library however you can use:
implicit class IntContext(val sc: StringContext) {
def i(args: Any*): Int = {
val orig = sc.s(args: _*)
orig.replace(" ", "").toInt
}
}
i"1 000 000" // res0: Int = 1000000
Note that starting Scala 2.13, underscore is accepted as a numeric literal separator:
val x = 1_000_000
// x: Int = 1000000
val pi = 3_14e-0_2
// pi: Double = 3.14
You can now write lengthy numeric literals that have a great readability score many thanks to the update done in Java 7. Read More on Adeva's blog https://adevait.com/java/5-best-and-worst-practices-in-java-coding
Before using Underscore:
int minUploadSize = 05437326;
long debitBalance = 5000000000000000L;
float pi = 3.141592653589F;
After making use of Underscore:
int minUploadSize = 05_437_326;
long debitBalance = 5_000_000_000_000_000L;
float pi = 3.141_592_653_589F;
The above-written declarations in Java show the importance of using underscores in numeric literals to improve the readability of codes. When you compare the two declarations above, you would be able to deduce that the one with included underscores is more readable compared to the other one.
I'm new to scala and trying to understand the right way to think about subtypes, so here's a simple example.
Let's say I want to make a function truncation() that takes a number and rounds it down to a few decimals places and returns the result. I might go about this as,
def truncation(number:Double, level:Int)={
math.floor(number * math.pow(10,level)) / math.pow(10,level)
}
truncation(1.2345, 2)
res0: Double = 1.23
But I probably also want this function to work with other numeric types besides Double, such as Float.
So how should I think about generalizing this function to work well with multiple types?
I'm thinking I should be using generic types such as
def truncation [A](number:A, level:Int):A={
math.floor(number * math.pow(10,level)) / math.pow(10,level)
}
but this doesn't compile.
In the case of just two types, I see that the Either type is a good option. But in the more general case,maybe I'll want to be able to handle Ints as well, and have different implementations that match on the type of the input object.
What's the best way to be thinking about this? Thanks for your help.
For a generic that you want to constrain to numeric types, you can use Numeric:
def truncation[T](number: T, level:Int)(implicit n: Numeric[T]) = {
import math._
val doubleValue = n.toDouble(number)
floor(doubleValue * pow(10,level)) / pow(10,level)
}
Or equivalently:
def truncation[T : Numeric](number: T, level:Int) = {
import math._
val doubleValue = implicitly[Numeric[T]].toDouble(number)
floor(doubleValue * pow(10,level)) / pow(10,level)
}
These will work for Ints, Doubles, Floats, and other numeric types.
The first example uses an implicit parameter, which you can read about here. The second version uses a context bound, which you can read about here together with the implicitly operator, which you can read about here. Finally, read the documentation of Numeric here to see all the available methods.
Note that the versions above both return Double. If you want them to return T (whatever the input type is), you can try:
def truncation[T : Numeric](number: T, level:Int): T = implicitly[Numeric[T]] match {
case n:Fractional[T] =>
val tenPow = n.fromInt(math.pow(10, level).toInt)
n.div(n.fromInt(n.toInt(n.times(number, tenPow))), tenPow)
case n:Integral[T] => number
}
For some reason (that escapes me), Scala math library does not have a pow-function for integers, but only for Doubles.
I need a square function for integers and was figuring what might be the usual way to do this in Scala.
object TestX extends App {
def pow2(v: Int)= v*v
//class MyRichInt( val v: Int ) {
// def ² : Int = v*v // says: "illegal character" for UTF-8 power-of-two
//}
println( pow2(42) )
//println( 42² )
println( math.pow(42,2).toInt )
}
I was surprised to see that the '²' character is not liked by Scala. Maybe it's taken to be a number? Usually all kinds of weird Unicode values are valid and using 42² in code would, indeed, be fancy.
Never mind. Should I shut up and just start using my own pow2 function?
Yes, use your own pow2. If you need higher powers, you probably won't have room in an Int anyway. Consider using BigInt.pow:
scala> BigInt(40).pow(40)
res0: scala.math.BigInt = 12089258196146291747061760000000000000000000000000000000000000000
Of course, if you need not N2 but 2N, just use shifts. (1 << k = 2k) These work with BigInt also.
Use backticks for Unicode characters, and implicit classes (Scala 2.10) to add operation on arbitrary types:
implicit class PowerInt(i: Int) {
def `²`: Int = i * i
}
Usage:
3 `²`
Result:
9
I am reading Scala and I am wondering ...
Why
val capacity : Int
instead of
val Int capacity.
Any reason why this choice was made. If not, it does not seem to me like a good choice to move away from the Java way of declaring it. Would have made the transition from Java to Scala easier (not by much, but little bit)
Because the majority of the time you can leave off the Int part. Scala has a much neater system of type inference than Java does.
I think I read a statement by Martin Odersky himself somewhere saying that this decision was also made in order to improve readability. This is certainly the case, e.g. compare
val Double number = ...
val Array[(Seq[String], Map[Seq[String], Double])] something = ...
val String pattern = ...
with
val number : Double = ...
val something : Array[(Seq[String], Map[Seq[String], Double])] = ...
val pattern : String = ...
Most of the time you need to find names of references/mathods fast (visually), not types.
x : T is the standard notation for types in logic and many programming languages. C and its descendants, with Java among them, deviates from this. But the type notation of C is really awful (try to write down the type for some moderately complicated higher order function like map).
Also, with this notation it is easy to leave out the type (as Wysawyg has already written), or to add a type inside an expression.
In Programming in Scala it says the technical reason for this syntax is it makes the type inference easier.
Here's an example to Wysawyg's statement:
val capacity = 2
But you typically might not do this with just a val.
trait Foo {
def capacity = 2 // Allow child classes to override and decide the value later
}
// Force instances of Bar to set the value
class Bar( override val capacity : Int ) extends Foo
// Have Bat determine it on the fly
trait Bat extends Foo {
def onlyAThird : Int
override def capacity = onlyAThird * 3
}
(I tried to insert this as a comment, but alas, no formatting.)
I think Daniel thought of something like that:
val a = 7
val b: Int = 8
var x = "Foo"
var y: String = "Bar"
def sum (a: Int, b: Int) = a + b
def mul (a: Int, b: Int): Int = a * b
The type can often be inferred.