i have a line of code which doesn’t work as i expect it too:
parentspermission x y = if x && y == False then print(“no”) else print (“yes”)
when i run parentspermission False False in ghci it gives me “yes” instead of “no” as it should be when false && false is false
this may not be worth mentioning but i am a beginner to haskell ive had some experience in python before and i am against using ai to learn haskell, i want to do it the old school way
a little addition is that when i ran parentspermission True False i got “no” as expected but when i ran parentspermission False True i somehow got “yes”
Check the precedences of (&&)
and (==)
. Neither function is magical in the language.
my understanding of this is the order i place && and ==, i would have usually placed a singlar equal sign after x && y but this isnt possible as a single equal sign is used to define functions.
The fix was to put x && y in parenthesis like so, (x && y) == False.
Noting that you are new to Haskell, you do not need ( )
around the "no"
and "yes"
values. To apply a function f :: a -> b
to x :: a
, you write f x
. Accordingly, you can write print "no"
.
Also, here, if you want Haskell code to be presented nicely, you can put it between ‘fences’ (each on their own lines) before and after the code ~~~haskell
(opening fence) and ~~~
(closing fence). For example:
parentspermission :: Bool -> Bool -> IO ()
parentspermission x y = if (x && y) == False then print “no” else print “yes”
A second also: print "no"
is equivalent to putStrLn (show "no")
. As "no"
is a String
, it may be that you do not actually want to output show "no"
but simply "no"
. That is because:
> show "no" == "\"no\""
True
(where \"
is an escaped double quote character in a Haskell string).
I’d also add to this that I’d probably usually write if not (x && y) then ... else ...
instead of (x && y) == False
in the conditional.
Edit: Also, welcome to Haskell
Building on @slow-dive 's suggestion, there is a helpful (non-AI) tool named hlint
:
which can help you learn by thinking through its suggestions.
For example, if you put your code in a module:
module MyModule
( parentspermission
) where
parentspermission :: Bool -> Bool -> IO ()
parentspermission x y = if (x && y) == False then print ("no") else print ("yes")
and command hlint MyModule
, it offers up (but in colour):
MyModule.hs:6:28-44: Suggestion: Redundant ==
Found:
(x && y) == False
Perhaps:
not (x && y)
MyModule.hs:6:57-62: Warning: Redundant bracket
Found:
("no")
Perhaps:
"no"
MyModule.hs:6:75-81: Warning: Redundant bracket
Found:
("yes")
Perhaps:
"yes"
3 hints
Thx i will check this out