Elm returning integer instead of Bool, compiler bug? - boolean

Function signature clearly states that it should return a Bool so why is the function returning 96? What is more, compiler thinks that 96 is actually a Bool. Is this a bug?
> isLeapYear year =\
| (modBy 4 year == 0) && (modBy 100 year /= 0) || (modBy 400 year == 0)
<function> : Int -> Bool
> isLeapYear 1996
96 : Bool
It seems to work sometimes though:
> isLeapYear 2000
True : Bool
> isLeapYear 1800
False : Bool

This is a compiler bug which I filed last year and which has now been fixed.
It affects only the /= operator when one argument is 0: replacing (modBy 100 year /= 0) with (not (modBy 100 year == 0)) will work around the problem.
The bug has been fixed in the source repository, but I don't know when the fix will be released.

Related

Scala, find if value is between two integers

I have an array of values
guests [1,2G,5G,5,6,8lalala,74,2zooo,555,654,22,21,19,4,5,2,10,11]
I need to find if '6' is between 0 and 15
I have tried the following:
if(Math.min(0, guests.toInt) == Math.max(guests.toInt, 15)) return xxxxxx
I'm getting nothing, it seems as though my if statemented is skipped all together
Please note, i don't want to return a Boolean
This condition:
Math.min(0, guests.toInt) == Math.max(guests.toInt, 15)
will always fail.
For i between 0 and 15, Math.min(0, i) will always return 0.
For i between 0 and 15, Math.max(i, 15) will always return 15.
So you will compare 0 == 15.
For ints below 0 or above 15 you will have:
less than 0 == 15
or
0 == more than 15
What you actually wanted to write is:
val i = guests.toInt
if (0 <= i && i <= 15) xxxxxx
else { some other value }

SWIFT Variable used before being initialized [duplicate]

This question already has answers here:
Variable used before being initialized in function
(6 answers)
Closed 4 years ago.
I want to know why this code will not run. The error appears on the very last line (the print statement) (the last "letter grade") and says
"Variable 'letterGrade' used before being initialized"
let score = 86
var letterGrade: Character
if(score >= 90)
{
letterGrade = "A"
}
else if(score >= 80)
{
letterGrade = "C"
}
else if (score >= 70)
{
letterGrade = "C"
}
else if (score >= 60)
{
letterGrade = "D"
}
else if (score > 0)
{
letterGrade = "F"
}
print("Your letter grade is \(letterGrade)")
Yes, it is used before being assigned a grade (the compiler does not know that you've covered all the cases in your if statements before throwing this error - and in fact you haven't covered zero as #MartinR tells you ).
You could have a default value (in the UK a "U" is ungraded) by changing line 2 to
var letterGrade: Character = "U"
and better still use type inference to say
var letterGrade = "U"
You might also like to use a switch for this type of problem - look in the Swift documents using this link - https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html
But here is my version of your code using a switch
let score = 86
var letterGrade: Character
switch score {
case 90 ..< 100:
print("A")
case (80 ..< 90):
print("B")
case (70 ..< 80):
print("C")
case (0 ..< 70):
print("D")
default:
print("F")
}
This overcomes the problem of your compiler error.
Hope this helps you.
You cannot use a variable before initializing it (giving it an initial value).
You handled the cases where score >= 90 and score >= 80 and score >= 70 and score >= 60 and score > 0.
What if score was equal to 0? this case isn't handled, if it happened the variable letterGrade will stay uninitialized.
To fix this, you can use the answer by #stevenpcurtis, or you can replace the last else if statement with else only.
Also consider using a switch statement with a default case.

How to check if a number is a power of 2 in SWIFT

I find out a lot of example to solve it, but nothing in SWIFT. Please help
smthng like this
Input : n = 4
Output : Yes
2^2 = 4
Input : n = 7
Output : No
Input : n = 32
Output : Yes
2^5 = 32
I needed algorithm for checking if a number is a power of 2. like 4, 8, 16 , 32 , 64 .... is number power of two
Determining if an integer is a power of 2
from the Bit Twiddling Hacks
is almost verbatim translated to Swift:
func isPowerOfTwo(_ n: Int) -> Bool {
return (n > 0) && (n & (n - 1) == 0)
}
Example:
print(isPowerOfTwo(4)) // true
print(isPowerOfTwo(5)) // false
Or as a generic function, so that it can be used with all binary
integer types:
func isPowerOfTwo<T: BinaryInteger> (_ n: T) -> Bool {
return (n > 0) && (n & (n - 1) == 0)
}
Example:
print(isPowerOfTwo(Int16(4))) // true
print(isPowerOfTwo(UInt8(5))) // false
Or as a protocol extension:
extension BinaryInteger {
var isPowerOfTwo: Bool {
return (self > 0) && (self & (self - 1) == 0)
}
}
Example:
print(1048576.isPowerOfTwo) // true
print(Int(50).isPowerOfTwo) // false
Partial answer:
If it's a FixedWidthInteger and it's positive and its non zero bit count is 1, then it is a power of 2.
let x = 128
if x > 0 && x.nonzeroBitCount == 1
{
// power of 2
}
For a floating point number, I think you can just test the significand. If it is exactly 1, the number is a power of 2.
let x: Double = 4
if x > 0 && x.significand == 1
{
// Power of 2
}
I haven't checked that in a Playground yet, so it might be wrong.
let numberToBeChecked = 4
result = numberToBeChecked.squareRoot()
If result%1 == 0 {
print(“4 is a power of 2”) } else {
print(“4 is not a power of 2”)
}
//note: result%1== 0 checks if result is a whole number.
Hope this works.

Arithmetically simulate 32-bit integer overflow

Is there a way to arithmetically simulate 32-bit, twos-complement integer overflow with numbers of a type whose value space is a strict superset of that of the 32-bit twos-complement integers? I need to perform such an operation in, for example, WolframAlpha, which has no explicit typing and no type casting.
The output of my desired convertTo32BitSignedInt(aValue) function needs to be the same as if I had cast the value in a language that supports it, such as Java: (int)aValue.
By example, the output of convertTo32BitSignedInt(17643225600) needs to be 463356416, the same as I had used the following cast (int)17643225600.
For the moment, my convertTo32BitSignedInt function (in pseudo code) looks like this and I am pretty sure it's not the better solution.
if(x > 2147483647 && floor(x / 2147483647 ) == 1){
return (x - 2*2147483648);
}else if(x > 2147483647 && (x % 2147483647 == 0) && (x % 2 == 0)){
return -1 * (x / 2147483647);
}else if(x > 2147483647 && (x % 2147483647 == 0) && (x % 2 > 0)){
return -1 * ((x - 2147483647) / 2147483647) + 2147483647;
}else if(x > 2147483647 && (x % 2147483647 > 0) && (x % 2 == 0)){
return -1 * floor(x / 2147483647) + (x % 2147483647);
}
//...
Use Case:
I try to demonstrate a certain behavior that will occures when there is a 32-bit signed integer overflow in a java program using a recursive implementation of the factorial function.
public int factorial(int n) {
return n == 1 || n==0 ? 1 : n * factorial(n - 1);
}
This int implementation, for factorial(13) gives 1932053504, because 13 * 479001600 > 2147483647, the 32-bit signed integer maximum value.
I use WolframAlpha for the demonstration. WolframAlpha allows numbers > 2147483647 and I want to simulate these number as 32-bit integer numbers. WolframAlpha gives the real answer which is 6227020800. I would like to be able to convert 6227020800 as 1932053504.
Edit: this is a rip & replace of my initial answer
You can do something roughly like this:
convertTo32BitSignedInt(aValue) {
bits32 = BitAnd(aValue, BitShiftLeft(1, 32) - 1);
sign = BitShiftRight(bits32, 31);
return bits32 - BitShiftLeft(sign, 32);
}

Reducing the number of brackets in Swift

Does anyone know if there is a way to use some kind shorthand in swift? more specifically, leaving out the braces in things like IF statements... eg
if num == 0
// Do something
instead of
if num == 0
{
// Do something
}
Those braces become rather space consuming when you have a few nested IF's.
PS. I do know I can do the following:
if num == 0 {
// Do something }
But I'm still curious if that sort of thing is possible
You can do that :
let x = 10, y = 20;
let max = (x < y) ? y : x ; // So max = 20
And so much interesting things :
let max = (x < y) ? "y is greater than x" : "x is greater than y" // max = "y is greater than x"
let max = (x < y) ? true : false // max = true
let max = (x > y) ? func() : anotherFunc() // max = anotherFunc()
(x < y) ? func() : anotherFunc() // code is running func()
This following stack : http://codereview.stackexchange.com can be better for your question ;)
Edit : ternary operators and compilation
By doing nothing more than replacing the ternary operator with an if else statement, the build time was reduced by 92.9%.
https://medium.com/#RobertGummesson/regarding-swift-build-time-optimizations-fc92cdd91e31#.42uncapwc
In swift you have to add braces even if there is just one statement in if:
if num == 0 {
// Do something
}
You cannot leave the braces, that how swift if statement work.
You could use a shorthand if statement like you would in objective-c:
num1 < num2 ? DO SOMETHING IF TRUE : DO SOMETHING IF FALSE
Swift 2.0 update
Method 1:
a != nil ? a! : b
Method 2: Shorthand if
b = a ?? ""
Referance: Apple Docs: Ternary Conditional Operator
and it does work,
u.dob = (userInfo["dob"] as? String) != nil ? (userInfo["dob"] as! String):""
I am replacing a json string with blank string if it is nil.
Edit: Adding Gerardo Medina`s suggestion...we can always use shorthand If
u.dob = userInfo["dob"] as? String ?? ""
It is called shorthand if-else condition. If you are into iOS development in Swift, then you can also manipulate your UI objects' behaviour with this property.
For e.g. - I want my button to be enabled only when there is some text in the textfield. In other words, should stay disabled when character count in textfield is zero.
button.enabled = (textField.characters.count > 0) ? true : false
its very simple :
in Swift 4
playButton.currentTitle == "Play" ? startPlay() : stopPlay()
Original Code is
if playButton.currentTitle == "Play"{
StartPlay()
}else{
StopPlay()
}
You could always put the entire if on one line:
if num == 0 { temp = 0 }