Many books and tutorials explain language features with small scripts that do asserts. If all the assertions pass, the process has an exit code of 0, and if any one fails, the process has a non-zero exit code. For example, in Python:
assert type(int) == type
assert len(list(x for x in range(3))) == 3
assert {'x': 1}['x'] == 1
and in Lua:
assert(type(7.299E-3) == "number")
assert(#{10, 20, 30} == 3)
assert(utf8.len("cafés") == 5)
In Ruby we can fake it in a nice way:
fail unless 5.send(:abs) == 5
fail unless 5.send('abs') == 5
fail unless 5.abs == 5
But I'm having trouble finding the equivalent in Haskell. When I tried to use error directly, in this script:
main = do
{ 1 == 1 || error "nope"
; 3 == 3 || error "nope"
; 8 == 8 || error "nope"
}
I get the error
error:
• Couldn't match expected type ‘m a0’ with actual type ‘Bool’
• In a stmt of a 'do' block: 1 == 1 || error "nope"
which makes sense given the expected type of main. Now I was able to do what I wanted by writing my own module on the side:
module SimpleAssert (assertAll) where
import Data.List (all)
assertAll assertions =
if all ((==) True) assertions
then return "ok"
else error "Assertion failure"
Then my script is the relatively clean:
import SimpleAssert (assertAll)
main = do
assertAll
[ 1 == 1
, 3 == 3
, 8 == 8
]
However it not as stand-alone as in the other languages (nor does it give me any indication of where the actual assertion failed, but I can live with that). Is there a way in Haskell to do without the external assert function? I do know about unit tests in Haskell, but that too has some "overhead." Perhaps the overhead is fine and proper, and maybe an external function is the right way to go, but I'm interested to know if Haskell supports some kind of lightweight approach to this. Does such a (lightweight) way exist?
Not fully sure if this meets your needs, but one simple option is to use unless:
main = do
unless (1 == 1) (error "nope")
unless (3 == 3) (error "nope")
unless (8 == 8) (error "nope")
and you could of course easily factor out a separate "assert" function from this if you want to.
Related
I was wondering if there is a simpler or shorter way to write repetitive conditions like x == 1 && y == 1 && z == 1?
When it is (exactly) repeated code, you should consider to extract the statement into a method and give a meaningfull name, which you know from the context where it is used. This makes the requirement (reading the code) easier to understand, at the point where it is used. And it makes it also easier to spot the it is always the same condition.
if (conditionName(x, y, z)) {
}
fun boolean conditionName(int x, int y, int z) {
return x == 1 && y == 1 && z == 1;
}
I cannot think of a shorter statement for the condition, but a method extraction will improve your code readability, which should be your overall goal.
You could consider using predicates using all. For example:
listOf(x, y, z).all {it == 1}
This will return true when x==1, y==1, and z==1.
If the goal is to shorten what you want, there's not much legroom as your boolean expression is already very concise. Some of the other answers have illustrated how to make what you want more readable, however.
You can make a convenience function for this kind of repeated code (or if you just need it to be more readable, or safer to edit):
fun <T> T.allEqual(vararg items: T) = items.all { it == this }
// or you could make the receiver the first parameter instead, this is just
// more explicit about which item is the value being compared against
1.allEqual(x, y, z)
But no, there isn't any other shorthand built into the language as far as I'm aware - conditions like x == 1 chained with boolean operators are about as simple as it can get! If you want to check multiple things without repeating yourself, any and all make that easy, while being flexible for all kinds of situations, and allowing the user to put together the functionality they need with those more general functions.
If you specifically want a version of all that does a simple comparison to a single value, and doesn't require creating an iterable like listOf, you have to write your own with those tools (which is basically what I've done). It's up to you if you think it's worth it!
If it makes sense you could hold those variables in a class
data class XYZ(
val x: Int,
val y: Int,
val z: Int)
And compare your instance with XYZ(1, 1, 1);
Or if it's just those three variables, you could write
if (Triple(x, y, z) == Triple(1, 1, 1))
val x = 1
val y = 1
var z = 1
println("$x$y$z" == "111") // prints 'true'
z = 2
println("$x$y$z" == "111") // prints 'false'
A Python code of a program that reads an integer, and prints the integer is a multiple of either 2 or 5 but not both.
First off, SO is not a forum to ask people to solve your homework without first putting effort yourself. you could have written a simple naive solution with if-else statements and posted that in your question, asking for a better way to do this.
That being said, I'm still adding my approach because I think you should know that a beautiful and simple way would be to just use an XOR check:
n = int(input("Input a number: "))
answer = True if (n % 2 == 0) != (n % 5 == 0) else False
print(answer)
I'm assuming the user will always input a value that can be cast as an integer. You can take care of the error handling process. Once the number has been read, I do a simple XOR check to return True if the number is only divisible by either 2 or 5 but not both, and False in all other cases. This works because bool(a)!=bool(b) gives True only when bool(a) and bool(b) evaluate to different things.
Demonstration:
def check(n):
return (n%2 == 0) != (n%5 ==0)
print(check(2)) # Out: True
print(check(5)) # Out: True
print(check(10)) # Out: False
print(check(3)) # Out: False
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 3 years ago.
I am trying to implement Euclid's algorithm for computing the greatest common divisor using recursion. Below is the code for the same.
def euclid(a,b):
if a>b:
r=a%b
if (r == 0):
return b
else:
a=b
b=r
euclid(a,b)
print(euclid(20,4)) # Returns 4
print(euclid(20,8)) # Returns None
For the first data set, I get the correct result. But for euclid(20,8) I get a return of None.
While checking in the debugger, I did see the return value of b become 4 but then for some reason, my code jumps to euclid(a,b) and returns None.
The major takeaway here would be to understand why the code does not return 4 but jumps to the euclid(a,b) and return None.
Please refrain from giving alternative code solutions but you are very much encouraged to point out the reason for the current behaviour of the code.
The reason for that code to return None at some point is that in your control flow you eventually end up in a situation where there is no return statement, e.g. for a <= b in your first if or when r != 0 in your second if. The default behavior of Python in that case is to return None, as you seems to have discovered the hard way.
def euclid(a,b):
if a>b:
r=a%b
if (r == 0):
return b
else: # <--- no `return` in this branch!
a=b
b=r
euclid(a,b)
# else: # <--- no `return` in this branch!
# ...
Here is an updated version of your code, that addresses that and also a number of other issues:
the name of the function should be meaningful: Euclid is kind of popular and there is a bunch of things named after him, better specify that you actually want to compute the greatest common divisor (GCD)
the first if is not really needed, as it is taken care of by the subsequent code: computing r and the recursive call will take care of swapping a and b if a < b, and if a == b then r == 0, so you b is being returned directly
a = b and b = r are useless, do not use them, just have your recursive call use b and r directly
the second if can be written more clearly in one line
def gcd_euclid_recursive(a, b):
r = a % b
return gcd_euclid_recursive(b, r) if r else b
gcd_euclid_recursive(120, 72)
# 24
gcd_euclid_recursive(64, 120)
# 8
You don't actually return anything in the else path so it just assumes you know best and returns None for you.
The only reason you get 4 for print(euclid(20,4)) is because 4 is a factor of 20 so never uses the else path. Instead it returns b immediately. For anything else, the thing returned from the first recursive call to euclid() will always be None (even if a lower call to that function returns something, you throw it away when returning from the first call).
You need return euclid(a,b) rather than just euclid(a,b).
As an aside (this isn't necessary to answer your specific question but it goes a long way toward improving the implementation of the code), I'm not a big fan of the if something then return else … construct since the else is totally superfluous (if it didn't return, the else bit is automatic).
Additionally, you don't need to assign variables when you can just change what gets passed to the next recursive level.
Taking both those into account (and simplifying quite a bit), you can do something like:
def euclid(a, b):
if b == 0: return a
return euclid(b, a % b)
Your code has an indentation error and one path is missing in your code(r!=0). It should be
def euclid(a,b):
if a>=b:
r=a%b
if (r == 0):
return b
return euclid(b, r)
else:
return euclid(b, a)
Can you have multiple evaluations in your WHEN clause?
For example is there a way to do something like this:
when (x == "Open" and y == "Ready") $ do...
I can get a single condition to work, but what if I need both to be true?
How about something like
when (x == "Open" && y == "Ready") $ do
...
&& is just a normal infix operator defined as
True && a = a
False && _ = False
Notice that with laziness this has exactly the same short circuiting properties we get in other languages!
On a totally separate note, instead of using strings to represent different states the Haskell-ish way would be to define your own type
data StateOfFoo = Ready
| Open
| Closed
| ...
deriving(Eq)
and then use x == Open && y == Ready for example. This way you make it clear in the types what you expect x and y to be.
How do I display a value whether it is true or false in groovy? I'm using Eclipse as my IDE.
assert 4 * ( 2 + 3 ) - 6 == 14 //integers only
And also I don't understand 'assert' too well in Groovy. Is it like an if() statement/boolean in Java?
What role does 'assert' play in Groovy?
An assertion is similar to an if, it verifies the expression you provide: if the expression is true it continues the execution to the next statement (and prints nothing), if the expression is false, it raises an AssertionError.
You can customize the error message providing a message separated by a colon like this:
assert 4 * ( 2 + 3 ) - 5 == 14 : "test failed"
which will print:
java.lang.AssertionError: test failed. Expression: (((4 * (2 + 3)) - 5) == 14)
but I had to change the values of your test, in order to make it fail.
The use of assertions is up to your taste: you can use them to assert something that must be true before going on in your work (see design by contract).
E.g. a function that needs a postive number to work with, could test the fact the argument is positive doing an assertion as first statement:
def someFunction(n) {
assert n > 0 : "someFunction() wants a positive number you provided $n"
...
...function logic...
}
Groovy asserts are now quite impressive! They will actually print out the value of every variable in the statement (which is fantastic for debugging)
for example, it might print something like this if b is 5, a is {it^2} and c is 15:
assert( a(b) == c)
. | | | |
. 25 | != 15
. 5
(Well--something like that--Groovy's would probably look a lot better).
If we could just get this kind of print-out on an exception line...
assert 'asserts' that the result of the expression will be a true