Handling long type argument in Scala - scala

object LPrimeFactor {
def main(arg:Array[String]):Unit = {
start(13195)
start(600851475143)
}
def start(until:Long){
var all_prime_fac:Array[Int] = Array()
var i = 2
(compile:compileIncremental) Compilation failed
integer number too large
Even though I changed the arg type to Long, it's still not fixed.

Pass the argument as a Long (notice the L at the end of the number):
start(600851475143L)
// ^

To create a Long literal you must add L to the end of it.
start(600851475143L)

Please remember literals values, if you has not any type direct suffix, the compiler try to get your numeric type values, such as 600851475143 as type Int, which is 32-bit length, two complement representation
MIN_VALUE = -2147483648(- 2 ^ 31)
MAX_VALUE = 2147483647(2 ^ 31 - 1)
So please add right suffix on the literal value, as 600851475143L

Related

Purescript: Convert Maybe Type to Type

The following simple code converts an Integer value to a string value and logs it.
module Main where
import Effect (Effect)
import Effect.Console (log)
import Prelude ((<>), Unit, discard)
import Data.Int (toStringAs, radix)
type CustomerFeedback = {
customerServiceScore :: Int,
productQualityScore :: Int,
onTimeDeliveryScore :: Int
}
feedback :: CustomerFeedback
feedback = {
customerServiceScore : 4,
productQualityScore : 2,
onTimeDeliveryScore : 6
}
stringifyCustomerFeedback :: CustomerFeedback -> String
stringifyCustomerFeedback feedback = "Service: " <> toStringAs (radix 10) feedback.customerServiceScore
main ∷ Effect Unit
main = do
log (stringifyCustomerFeedback(feedback))
However, running this code produces the following error:
Could not match type
Maybe Radix
with type
Radix
while checking that type Maybe Radix
is at least as general as type Radix
while checking that expression radix 10
has type Radix
in value declaration stringifyCustomerFeedback
Questions would be as follows:
How do you change the code above so it outputs a string as expected and not an error?
What's the point of a Maybe Radix type if using it where you would use a Radix causes an error? How do you use a Maybe value?
The idea of the radix function is that you give it a number and it creates a Radix from it. But not every number constitutes a valid Radix. For example, if you give it -5, it shouldn't work. And neither should 0 or 1 for example. For some technical reasons, radices above 32 are also deemed invalid.
So that's why it returns Maybe: it would be Nothing in case the number you gave it wasn't a "valid" radix.
And the use case for that function is when you don't actually know the number ahead of time. Like if you get it from the user. Or from some sort of config file or whatnot. In that case, if you get a Nothing, you would interpret that as "invalid user input" or "corrupted config file" and report an error accordingly. And you won't even get as far as calling toStringAs. This is one of the big selling points of static types: applied properly, they can force you to write a correct, reliable program, without ignoring edge cases.
However, in case you already know that you're interested in decimal radix, just use decimal. It's a Maybe-free constant provided by the library, along with some other frequently used ones, such as binary and octal.
stringifyCustomerFeedback feedback = "Service: " <> toStringAs decimal feedback.customerServiceScore

Big Int in scala

I'm new to Scala. I'm trying to create a test case for a simple factorial function.
I couldn't assign the result value in the assert statement. I'm getting
Integer number is out of range even for type Long error in IntelliJ.
test("Factorial.factorial6") {
assert(Factorial.factorial(25) == 15511210043330985984000000L)
}
I also tried to assign the value to val, using the 'L' literal, again it shows the same
message.
val b: BigInt = 15511210043330985984000000L
I'm clearly missing some basic stuff about Scala, I would appreciate your help, to solve this
The value you are giving is indeed larger than can be held in a Long, and that is the maximum size for a literal value in Scala. However you can initialise a BigInt using a String containing the value:
val b = BigInt("15511210043330985984000000")
and therefore
assert(Factorial.factorial(25) == BigInt("15511210043330985984000000"))

Using zero constant as long in a less verbose way [duplicate]

object LPrimeFactor {
def main(arg:Array[String]):Unit = {
start(13195)
start(600851475143)
}
def start(until:Long){
var all_prime_fac:Array[Int] = Array()
var i = 2
(compile:compileIncremental) Compilation failed
integer number too large
Even though I changed the arg type to Long, it's still not fixed.
Pass the argument as a Long (notice the L at the end of the number):
start(600851475143L)
// ^
To create a Long literal you must add L to the end of it.
start(600851475143L)
Please remember literals values, if you has not any type direct suffix, the compiler try to get your numeric type values, such as 600851475143 as type Int, which is 32-bit length, two complement representation
MIN_VALUE = -2147483648(- 2 ^ 31)
MAX_VALUE = 2147483647(2 ^ 31 - 1)
So please add right suffix on the literal value, as 600851475143L

Swift type inference and basic addition

Pretty new to Swift and learning about data types.
let partNumber = 3.2
let wholeNumber = 2
partNumber + wholeNumber //Binary operator '+' cannot be applied to operands of type 'Double' and 'Int'
3.2 + 2 // outputs 5.2
I understand that partNumber is a Double type and wholeNumber is an Int. What I don't understand is why playground errors out when I attempt to add both constants together. To add confusion the addition works when not assigned as a constant.
The + operator does not support adding a Double and and Integer together in this way
If you change up your code to make sure wholeNumber is a Double type, then it'll work
let partNumber = 3.2
let wholeNumber: Double = 2
let result = partNumber + wholeNumber
This is all covered in the Swift book under Numeric Type Conversion.
Some relevant quotes from the subsection titled "Integer and Floating-Point Conversion":
Conversions between integer and floating-point numeric types must be made explicit
This is followed by an example similar to your code. Your code needs a cast:
let partNumber = 3.2
let wholeNumber = 2
partNumber + Double(wholeNumber)
and:
The rules for combining numeric constants and variables are different from the rules for numeric literals. The literal value 3 can be added directly to the literal value 0.14159, because number literals don’t have an explicit type in and of themselves. Their type is inferred only at the point that they’re evaluated by the compiler.
Which covers the second part of your question.
To add confusion the addition works when not assigned as a constant.
That doesn't "add to the confusion" at all. It's the answer. There is implicit coercion between numeric types for literals (what you call a "constant") but not for variables. It's as simple as that.

Swift float multiplication error

This code fails:
let element: Float = self.getElement(row: 1, column: j)
let multiplier = powf(-1, j+2)*element
with this error:
Playground execution failed: :140:51: error: cannot invoke '*' with an argument list of type '(Float, Float)'
let multiplier = powf(-1, j+2)*element
Bear in mind that this occurs in this block:
for j in 0...self.columnCount {
where columnCount is a Float. Also, the first line does execute and so the getElement method indeed returns a Float.
I am completely puzzled by this as I see no reason why it shouldn't work.
There is no implicit numeric conversion in swift, so you have to do explicit conversion when dealing with different types and/or when the expected type is different than the result of the expression.
In your case, j is an Int whereas powf expects a Float, so it must be converted as follows:
let multiplier = powf(-1, Float(j)+2)*element
Note that the 2 literal, although usually considered an integer, is automatically inferred a Float type by the compiler, so in that case an explicit conversion is not required.
I ended up solving this by using Float(j) instead of j when calling powf(). Evidently, j cannot be implicitly converted to a Float.