Haskell execution sequence - haskell

isOdd, isEven :: Int -> Bool
isOdd n
| n<=0 = False
| otherwise = isEven (n-1)
isEven n
| n<0 = False
| n==0 = True
| otherwise = isOdd (n-1)
I'm having trouble understanding this code,in isOdd,it only defines what is False,and then switch to isEven,so how does haskell know when is n odd?

There are two different functions here: isOdd and isEven. They are defined in terms of each other: A number is "not odd" if it is negative or zero, and "odd" if one less than that number is "even". A number is "not even" if it is negative, and "even" if it is zero or one less than that number is "odd".
It's a fairly unintuitive way to define these functions, but it has nothing to do with "execution sequence" or "evaluation order". In fact, Haskell compilers are allowed to execute any computation they want as long as it gives the correct value as a result and follows the lazy/strict semantics as specified in the Haskell Report.
A better implementation of these functions is as follows: (from the Prelude)
even, odd :: (Integral a) => a -> Bool
even n = n `rem` 2 == 0
odd = not . even
In other words, and integer-like thing is even if the remainder when you divide it by 2 is 0, and odd if it is not even.
Note: The INLINEABLE pragams in the link above are just an optimization, and can be ignored.

These functions are mutually recursive (each one can call the other one), with base cases. Lets follow an example evaluation using isOdd. First, I will start by changing the guards into the equivalent ifs for (hopefully) more clarity in this answer (though I would usually suggest using guards).
isOdd, isEven :: Int -> Bool
isOdd n =
if n <= 0
then False
else isEven (n-1)
isEven n =
if n < 0
then False
else if n == 0
then True
else isOdd (n-1)
Now, we can try stepping through an example evaluation[1]:
isOdd 3
==> if 3 <= 0 (Applying isOdd to 5 and expanding the body)
then False
else isEven (3-1)
==> isEven (3-1) (3 > 0)
==> if 2 < 0
then False
else if 2 == 0
then True
else isOdd (2-1)
==> isOdd (2-1) (4 > 0, so the first two branches aren't taken)
==> if 1 <= 0 (Applying isOdd to 1 and expanding the body)
then False
else isEven (1-1)
==> isEven 0
==> if 0 < 0
then False
else if 0 == 0
then True
else isOdd (0-1)
==> True (0 == 0, so the second branch is taken)
The intuition behind why these functions work is this: if a non-negative integer (natural number) n is greater than 0, it is odd if its predecessor (n-1) is even and it is even if its predecessor is odd. This is true since even and odd numbers alternate.
I would recommend stepping through an evaluation whenever you run into a function (or, in this case, pair of functions) that you don't understand using a small example like this.
[1]: Note for something that doesn't really matter for this question: I've slightly simplified when the expressions of the shape x-1 get reduced to the corresponding number.

this is called "mutual recursion" or "mutually recursive functions", as in the recursive functions you need to define the terminal state (or exit condition). However, your definition is not the best, here is a better alternative
isEven,isOdd :: Int -> Bool
isEven 0 = True
isEven n = isOdd (n - 1)
isOdd 0 = False
isOdd n = isEven (n - 1)
here the terminal condition is set for 0 (symmetrically) and mutual recursion will end up on one of them eventually.
Note that this is only defined for non-negative integers but not enforced with the type Int.
Your definition is not correct either but at least will terminate for negative numbers.

Related

How to tell if a number is a square number with recursion?

I solved the following exercise, but I'm not a fan of the solution:
Write the function isPerfectSquare using recursion, to tell if an
Int is a perfectSquare
isPerfectSquare 1 -> Should return True
isPerfectSquare 3 -> Should return False
the num+1 part is for the case for isPerfectSquare 0 and isPerfectSquare 1, one of the parts I don't like one bit, this is my solutiuon:
perfectSquare 0 1 = [0] ++ perfectSquare 1 3
perfectSquare current diff = [current] ++ perfectSquare (current + diff) (diff + 2)
isPerfectSquare num = any (==num) (take (num+1) (perfectSquare 0 1))
What is a more elegant solution to this problem? of course we can't use sqrt, nor floating point operations.
#luqui you mean like this?
pow n = n*n
perfectSquare pRoot pSquare | pow(pRoot) == pSquare = True
| pow(pRoot)>pSquare = perfectSquare (pRoot-1) pSquare
| otherwise = False
--
isPerfectSquare number = perfectSquare number number
I can't believe I didn't see it xD thanks a lot! I must be really tired
You can perform some sort of "binary search" on some implicit list of squares. There is however a problem of course, and that is that we first need an upper bound. We can use as upper bound the number itself, since for all integral squares, the square is larger than the value we square.
So it could look like:
isPerfectSquare n = search 0 n
where search i k | i > k = False
| j2 > n = search i (j-1)
| j2 < n = search (j+1) k
| otherwise = True
where j = div (i+k) 2
j2 = j * j
To verify that a number n is a perfect square, we thus have an algorithm that runs in O(log n) in case the integer operations are done in constant time (for example if the number of bits is fixed).
Wikipedia suggests using Newton's method. Here's how that would look. We'll start with some boilerplate. ensure is a little combinator I've used fairly frequently. It's written to be very general, but I've included a short comment that should be pretty explanatory for how we'll plan to use it.
import Control.Applicative
import Control.Monad
ensure :: Alternative f => (a -> Bool) -> a -> f a
ensure p x = x <$ guard (p x)
-- ensure p x | p x = Just x
-- | otherwise = Nothing
Here's the implementation of the formula given by Wikipedia for taking one step in Newton's method. x is our current guess about the square root, and n is the number we're taking the square root of.
stepApprox :: Integer -> Integer -> Integer
stepApprox x n = (x + n `div` x) `div` 2
Now we can recursively call this stepping function until we get the floor of the square root. Since we're using integer division, the right termination condition is to watch for the next step of the approximation to be equal or one greater to the current step. This is the only recursive function.
iterateStepApprox :: Integer -> Integer -> Integer
iterateStepApprox x n = case x' - x of
0 -> x
1 -> x
_ -> iterateStepApprox x' n
where x' = stepApprox x n
To wrap the whole development up in a nice API, to check if a number is a square we can just check that the floor of its square root squares to it. We also need to pick a starting approximation, but we don't have to be super smart -- Newton's method converges very quickly for square roots. We'll pick half the number (rounded up) as our approximation. To avoid division by zero and other nonsense, we'll make zero and negative numbers special cases.
isqrt :: Integer -> Maybe Integer
isqrt n | n < 0 = Nothing
isqrt 0 = Just 0
isqrt n = ensure (\x -> x*x == n) (iterateStepApprox ((n+1)`div`2) n)
Now we're done! It's pretty fast even for large numbers:
> :set +s
> isqrt (10^10000) == Just (10^5000)
True
(0.58 secs, 182,610,408 bytes)
Yours would spend rather a longer time than the universe has got left computing that. It is also marginally faster than the binary search algorithm in my tests. (Of course, not hand-rolling it yourself is several orders of magnitude faster still, probably in part because it uses a better, but more complicated, algorithm based on Karatsuba multiplication.)
If the function is recursive then it is primitive recursive as are 90% of all recursive functions. For these folds are fast and effective. Considering the programmers time, while keeping things simple and correct is important.
Now, that said, it might be fruitful to cinsider text patterns of functions like sqrt. sqrt return a floating point number. If a number is a perfect square then two characters are ".0" at the end. The pattern might occur, however, at the start of any mantissa. If a string goes in, in reverse, then "0." is at the top of the list.
This function takes a Number and returns a Bool
fps n = (take 2.reverse.show $ (n / (sqrt n))) == "0."
fps 10000.00001
False
fps 10000
True

Prime number program in haskell

I was looking up a program in Haskell that tests if a given number is prime or not.
prime :: (Integral a) => a -> Bool
prime 1 = True
prime x = and [ x `mod` y /= 0 | y <- [2..(x-1)] ]
I don't understand what is the purpose of this and in: prime x = and [.
Although this question has been answered, please allow me to add a few things:
When examining the source of and, you get:
and :: [Bool] -> Bool
and = foldr (&&) True
First thing to notice is that and takes a list of Boolean variables, and returns a single Boolean variable, and that the expression x mod y /= 0 evaluates to True or False (Hence fitting the [Bool] requirement) .
More important to notice is that foldr is a lazy-fold. So a lazy fold here is optimal because && is a semi-strict operator. Hence a lazy fold in combination with a semi-strict operator will yield a short-circuit evaluation upon encountering the first occurence of a False. Hence in the cases of actual non-prime numbers, and will avoid evaluating the entire list, consequently saving you time as a result. Don't take my word for it, define your own strict version of and if you want (using the stricter foldl):
andStrict :: [Bool] -> Bool
andStrict x = foldl (&&) True
primeStrict :: (Integral a) => a -> Bool
primeStrict x = andStrict [x `mod` y /= 0 | y <- [2..(x-1)]]
Now run:
prime 2000000000
Notice how that was fast? Now do this, but interrupt it before it crashes your memory-stack:
primeStrict 2000000000
That was obviously slower, you were able to interrupt it. This is the role of and, and that is why and was written with foldr, and hence why it was chosen for the example code you posted. Hope that helps as a supportive answer.
The expression
[x `mod` y /= 0 | y <- [2..(x - 1)]
is a list of Bools because mod x y /= 0 (prefix notation because of backtick formatting) returns a Bool. The and function just does a logical AND of every element in a list, so
and [True, False] == False
and [True, True] == True
and performs a logical and operation on all elements of a list.
Primes are only divisible by one and themselves; this means that as soon as a divisor (without a remainder) exists between 2 inclusive and your x exclusive, the number is not a prime.
The list comprehension generates a list of Boolean values that correspond to whether your x is or is not divisible by numbers from within the said range.
As soon as any of them is false (a division occurred with a zero remainder), the number is not a prime.
Consider:
x = 7
[7 % 2 /= 0 -> True, 7 % 3 /= -> True, ...]
-- now applying and
True && True && ... && True evaluates to True
and can be represented as a more general operation that can be performed on lists - a fold using logical and. Such as: and' = foldr (&&) True.

How can a homemade Haskell program to check if an integer is even be written?

I'm very new to Haskell, with my only prior programming knowledge being in Python. I'm trying to write a program for a part of a homework assignment that will take an integer n and return either True or False depending on whether or not n is even. I'm trying to use if/then/else as well as the built-in mod function, but I just can't quite seem to nail down the proper syntax.
iseven n = mod n 2
if n == 0
then n = True
else n = False
If someone could point me in the right direction, it would be greatly appreciated.
If-then-else has the following form:
iseven n = if mod n 2 == 0 then True else False
See: http://www.haskell.org/haskellwiki/If-then-else
Or just forgo the True/False return values:
iseven n = mod n 2 == 0
Or better yet, just use the even function from the Prelude.
You just need to connect the two pieces you have and fix up the syntax problems.
isEven n = if n `mod` 2 == 0
then True
else False
But you don't need to compare True to True; you could just do the following:
isEven n = n `mod` 2 == 0
And if you want to get very Haskelly, you can make it pointfree:
isEven = (== 0) . (`mod` 2)

How is a recursive prime number checker written in Haskell?

I'm very new to Haskell (and functional programming in general), and I'm trying some basic exercises to try to get an understanding of the language. I'm writing a "naive" prime number checker that divides each number under the input to check if there is any remainder. The only constructs I've learned so far are comprehension lists and recursive functions, so I'm constrained to that. Here's what I'm trying:
isprime 1 = False
isprime 2 = True
isprime n = isprimerec n (n-1)
isprimerec _ 1 = False
isprimerec n t = if (n `rem` t) == 0 then False else isprimerec n (n-1)
The intention is that the user would use isprime n. Then isprime would use isprimerec to determine if the number is prime. It's a pretty round-about way of doing it, but I don't know any other way with my limited knowledge of Haskell.
Here's what happens when I try this:
isprimerec 10 9
Runs forever. I have to use Ctrl+C to stop it.
isprimerec 10 5
Returns False. The else part is never evaluated, so the function never calls itself.
I'm not sure why this is happening. Also, is this anywhere near close to how a Haskell programmer would approach this problem? (And I don't mean checking primality, I know this isn't the way to do it. I'm just doing it this way as an exercise).
The problem is in this line
isprimerec n t = if (n `rem` t) == 0 then False else isprimerec n (n-1)
You use (n - 1) as the second argument where it should be (t - 1). A further point, I think you want the isprimerec _ 1 case = True.
As to your more general question of whether or not this is idiomatic, I think you're on the right track. ghci has a decent command line debugger. I found this by putting your code in a file, loading it, and then issuing the command :break isprimerec. I then called your function and stepped through it with :step.
Your bug is a simple typo; at the end of isprimerec, your second parameter becomes n-1 instead of t-1. But that aside, the function isn't quite idiomatic. Here's the first pass of how I would write it:
isPrime :: (Ord a, Integral a) => a -> Bool
isPrime n | abs n <= 1 = False
isPrime 2 = True
isPrime n = go $ abs n - 1
where go 1 = False
go t = (n `rem` t /= 0) && go (t-1)
(I might call go something like checkDivisors, but go is idiomatic for a loop.) Note that this exposes the bug in your code: once go is local to isPrime, you don't need to pass n around, and so it becomes clearer that recursing on it is incorrect. The changes I made were, in rough order of importance:
I made isprimerec a local function. Nobody else would need to call it, and we lose the extra parameter.
I made the function total. There's no reason to fail on 0, and not really any reason to fail for negative numbers. (Technically speaking, p is prime if and only if -p is prime.)
I added a type signature. It's a good habit to get into. Using Integer -> Bool, or even Int -> Bool, would also have been reasonable.
I switched to interCaps instead of alllowercase. Just formatting, but it's customary.
Except I'd probably make things terser. Manual recursion is usually unnecessary in Haskell, and if we get rid of that entirely, your bug becomes impossible. Your function checks that all the numbers from 2 to n-1 don't divide n, so we can express that directly:
isPrime :: (Ord a, Integral a) => a -> Bool
isPrime n | abs n <= 1 = False
| otherwise = all ((/= 0) . (n `rem`)) [2 .. abs n - 1]
You could write this on one line as
isPrime :: (Ord a, Integral a) => a -> Bool
isPrime n = abs n > 1 && all ((/= 0) . (n `rem`)) [2 .. abs n - 1]
but I wouldn't be surprised to see either of these last two implementations. And as I said, the nice thing about these implementations is that your typo isn't possible to make in these representations: the t is hidden inside the definition of all, and so you can't accidentally give it the wrong value.
Your else branch is broken since it calls isprimerec n (n-1) every time. You probably ought to write isprimerec n (t-1) instead to have it count down.
You could also use a higher-order function all to make this a lot simpler.
isprime 1 = False
isprime n = all (\t -> n `rem` t /= 0) [2..(n-1)]
So OK, you've got the two bugs: your
isprimerec _ 1 = False
isprimerec n t = if (n `rem` t) == 0 then False else isprimerec n (n-1)
should have been
isprimerec _ 1 = True
isprimerec n t = if (n `rem` t) == 0 then False else isprimerec n (t-1)
or, with list comprehension,
isprime n = n>1 && and [ rem n t /= 0 | t <- [n-1,n-2..2] ]
(Internalize that extra parameter t, it was a technicality anyway! -- A-ha, but what's that and, you ask? It's just like this recursive function, foldr (&&) True :: [Bool] -> Bool.)
But now a major algorithmic drawback becomes visually apparent: we test in the wrong order. It will be faster if we test in ascending order:
isprime n = n>1 && and [ rem n t /= 0 | t <- [2..n-1] ]
or even much faster yet if we stop at the sqrt,
isprime n = n>1 && and [ rem n t /= 0 | t <- [2..q] ]
where q = floor (sqrt (fromIntegral n))
or test only by odds, after the 2 (why test by 6, if we've tested by 2 already?):
isprime n = n>1 && and [ rem n t /= 0 | t <- 2:[3,5..q] ]
where q = floor (sqrt (fromIntegral n))
or just by primes (why test by 9, if we've tested by 3 already?):
isprime n = n>1 && and [ rem n t /= 0 | t <- takeWhile ((<= n).(^2)) primes ]
primes = 2 : filter isprime [3..]
And why test the evens when filtering the primes through - isn't it better to not generate them in the first place?
primes = 2 : filter isprime [3,5..]
But isprime always tests division by 2 -- yet we feed it only the odd numbers; so,
primes = 2 : 3 : filter (noDivs (drop 1 primes)) [5,7..]
noDivs factors n = and [ rem n t /= 0 | t <- takeWhile ((<= n).(^2)) factors ]
And why generate the multiples of 3 (i.e. [9,15 ..] == map (3*) [3,5..]), only to test and remove them later? --
{- [5,7..]
== [j+i | i<-[0,2..], j<-[5]] -- loop unrolling, 3x:
== [j+i | i<-[0,6..], j<-[5,7,9]]
== 5:[j+i | i<-[0,6..], j<-[7,9,11]]
== 5:[7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43, ...
\\ [ 9, 15, 21, 27, 33, 39, ...
== [j+i | i<-[0,6..], j<-[ 9 ]]
-}
primes = 2:3:5: filter (noDivs (drop 2 primes))
[j+i | i<-[0,6..], j<-[7, 11]]
We can skip over the multiples of 5 in advance as well (as another step in the Euler's sieve, euler (x:xs) = x : euler (xs `minus` map (x*) (x:xs))):
-- [j+i | i<-[0, 6..], j<-[7, 11]] -- loop unrolling, 5x:
-- == 7:[j+i | i<-[0,30..], j<-[11,13,17,19,23,25,29,31,35,37]]
-- \\ [j+i | i<-[0,30..], j<-[ 25, 35 ]]
primes = 2:3:5:7: filter (noDivs (drop 3 primes))
[j+i | i<-[0,30..], j<-[11,13,17,19,23, 29,31, 37]]
... but that's already going far enough, for now.

When is the difference between quotRem and divMod useful?

From the haskell report:
The quot, rem, div, and mod class
methods satisfy these laws if y is
non-zero:
(x `quot` y)*y + (x `rem` y) == x
(x `div` y)*y + (x `mod` y) == x
quot is integer division truncated
toward zero, while the result of div
is truncated toward negative infinity.
For example:
Prelude> (-12) `quot` 5
-2
Prelude> (-12) `div` 5
-3
What are some examples of where the difference between how the result is truncated matters?
Many languages have a "mod" or "%" operator that gives the remainder after division with truncation towards 0; for example C, C++, and Java, and probably C#, would say:
(-11)/5 = -2
(-11)%5 = -1
5*((-11)/5) + (-11)%5 = 5*(-2) + (-1) = -11.
Haskell's quot and rem are intended to imitate this behaviour. I can imagine compatibility with the output of some C program might be desirable in some contrived situation.
Haskell's div and mod, and subsequently Python's / and %, follow the convention of mathematicians (at least number-theorists) in always truncating down division (not towards 0 -- towards negative infinity) so that the remainder is always nonnegative. Thus in Python,
(-11)/5 = -3
(-11)%5 = 4
5*((-11)/5) + (-11)%5 = 5*(-3) + 4 = -11.
Haskell's div and mod follow this behaviour.
This is not exactly an answer to your question, but in GHC on x86, quotRem on Int will compile down to a single machine instruction, whereas divMod does quite a bit more work. So if you are in a speed-critical section and working on positive numbers only, quotRem is the way to go.
A simple example where it would matter is testing if an integer is even or odd.
let buggyOdd x = x `rem` 2 == 1
buggyOdd 1 // True
buggyOdd (-1) // False (wrong!)
let odd x = x `mod` 2 == 1
odd 1 // True
odd (-1) // True
Note, of course, you could avoid thinking about these issues by just defining odd in this way:
let odd x = x `rem` 2 /= 0
odd 1 // True
odd (-1) // True
In general, just remember that, for y > 0, x mod y always return something >= 0 while x rem y returns 0 or something of the same sign as x.

Resources