I want to write a Haskell program that calculates the sum of numbers between 2 given numbers.
I have the following code:
sumInt :: Int -> Int -> Int
sumInt x y
| x > y = 0
| otherwise = x + sumInt x+1 y
But when I compile it I get the following error:
SumInt is applied to too few arguments.
I don't understand what I'm doing wrong. Any ideas?
You need parentheses around x+1:
| otherwise = x + sumInt (x + 1) y
The reason is that function application binds more tightly than operators, so whenever you see
f x <> y
This is always parsed as
(f x) <> y
and never as
f (x <> y)
Related
Is there a way to compactly write multiple definitions in haskell via case, without having to repeat, other than the input parameters, the exact same syntax? The only possible solution I can imagine so far is a macro.
Below is an example of defining binary max and min functions. Can we compress
max' x y
| x > y = x
| otherwise = y
min' x y
| x < y = x
| otherwise = y
into something like
(max',min') x y
| x (>,<) y = x
| otherwise = y
?
Edit:
I know this allows us to parametrize over the "grumpy face", but it seems like there still could be a more succinct form.
maxmin x y f
| f x y = x
| otherwise = y
max' x y = maxmin x y (>)
min' x y = maxmin x y (<)
Well, you can always do this:
select op x y
| x `op` y = x
| otherwise = y
max' = select (>)
min' = select (<)
I.e. extract the common parts into a function and turn the differences into parameters.
If I have a function, for example
f :: Int -> Int -> Int
f x y = x + y
and I want to have different functionality based on the parameters, I use pattern matching.
I have only found the syntax of how to match against concrete values, e.g.
f 0 y = y
Is it possible to match against something more general?
I would like to have different functionality in the case that the first parameter is less than 0. A second case could be if the second parameter exceeds a certain value.
You can use guards:
f x y | x < 0 = ...
f x y | y > someValue = ...
f x y | otherwise = ...
Sure, there is a mechanism called guards for that:
f x y | x < 0 = y
The problem:
You are given a function plusOne x = x + 1. Without using any other (+)s, define a recursive function addition such that addition x y adds x and y together.
(from wikibooks.org)
My code (it does not work -- endless loop):
plusOne x = x + 1
addition x y
| x > 0 = addition (plusOne y) (x-1)
| otherwise = y
Questions:
How to connect the plusOne function to the addition recursive function?
How should it be written?
You are mixing up x and y in your recursive case
addition x y | y > 0 = addition (plusOne x) (y - 1) -- x + y == (x + 1) + (y - 1)
| otherwise = x -- x + 0 = x
using == and 0
addition = add 0 where
add a y x | a == y = x
| otherwise = add (plusOne a) y (plusOne x)
I am trying to write a simple function that takes three Int values and returns the sum of the minimum and maximum integers out of these three.
My code:
summinmax3 :: Int -> Int -> Int -> Int
summinmax3 x y z =
if (x > y && z < y)
then (x + z)
else if (y > x && z < x)
then (y + x)
else if (z > x && y < X)
then (y + z)
The code returns the error syntax error in expression (unexpected '}'), possibly due to bad layout
Any help would be appreciated
You're missing else. Every if needs both then and else, otherwise the return value wouldn't be determined, e.g. what should happen if x isn't even here?
add3IfEven x = if even x then x + 3
However, your compiler (Hugs) doesn't use your actual code, instead it transforms it into something else with curly braces:
{if … then … else … }
Since you're missing that last else, the } is unexpected. So make sure to add the correct else case. By the way, you can simply solve this exercise with maximum [x + y, x + z, y + z].
I was reading the Haskell Prelude and finding it pretty understandable, then I stumbled upon the exponention definition:
(^) :: (Num a, Integral b) => a -> b -> a
x ^ 0 = 1
x ^ n | n > 0 = f x (n-1) x
where f _ 0 y = y
f x n y = g x n where
g x n | even n = g (x*x) (n `quot` 2)
| otherwise = f x (n-1) (x*y)
_ ^ _ = error "Prelude.^: negative exponent"
I do not understand the need for two nested wheres.
What I understood so far:
(^) :: (Num a, Integral b) => a -> b -> a
The base must be a number and the exponent intege, ok.
x ^ 0 = 1
Base case, easy.
g x n | even n = g (x*x) (n `quot` 2)
| otherwise = f x (n-1) (x*y)
Exponention by squaring... kind of ... Why is the f helper needed? Why are f and g given single letter names? Is it just optimization, am I missing something obvious?
_ ^ _ = error "Prelude.^: negative exponent"
N > 0 was checked before, N is negative if we arrived here, so error.
My implementation would be a direct translation to code of:
Function exp-by-squaring(x, n )
if n < 0 then return exp-by-squaring(1 / x, - n );
else if n = 0 then return 1; else if n = 1 then return x ;
else if n is even then return exp-by-squaring(x * x, n / 2);
else if n is odd then return x * exp-by-squaring(x * x, (n - 1) / 2).
Pseudocode from wikipedia.
To illustrate what #dfeuer is saying, note that the way f is written it either:
f returns a value
or, f calls itself with new arguments
Hence f is tail recursive and therefore can easily be transformed into a loop.
On the other hand, consider this alternate implementation of exponentiation by squaring:
-- assume n >= 0
exp x 0 = 1
exp x n | even n = exp (x*x) (n `quot` 2)
| otherwise = x * exp x (n-1)
The problem here is that in the otherwise clause the last operation performed is a multiplication. So exp either:
returns 1
calls itself with new arguments
calls itself with some new arguments and multiplies the result by x.
exp is not tail recursive and therefore cannot by transformed into a loop.
f is indeed an optimization. The naive approach would be "top down", calculating x^(n `div` 2) and then squaring the result. The downside of this approach is that it builds a stack of intermediate computations. What f lets this implementation do is to first square x (a single multiplication) and then raise the result to the reduced exponent, tail recursively. The end result is that the function will likely operate entirely in machine registers. g seems to help avoid checking for the end of the loop when the exponent is even, but I'm not really sure if it's a good idea.
As far as I understand it exponentiation is solved by squaring as long as the exponent is even.
This leads to the answer why f is needed in case of an odd number - we use f to return the result in the case of g x 1, in every other odd case we use f to get back in the g-routine.
You can see it best I think if you look at an example:
x ^ n | n > 0 = f x (n-1) x
where f _ 0 y = y
f x n y = g x n
where g x n | even n = g (x*x) (n `quot` 2)
| otherwise = f x (n-1) (x*y)
2^6 = -- x = 2, n = 6, 6 > 0 thus we can use the definition
f 2 (6-1) 2 = f 2 5 2 -- (*)
= g 2 5 -- 5 is odd we are in the "otherwise" branch
= f 2 4 (2*2) -- note that the second '2' is still in scope from (*)
= f 2 4 (4) -- (**) for reasons of better readability evaluate the expressions, be aware that haskell is lazy and wouldn't do that
= g 2 4
= g (2*2) (4 `quot` 2) = g 4 2
= g (4*4) (2 `quot` 2) = g 16 1
= f 16 0 (16*4) -- note that the 4 comes from the line marked with (**)
= f 16 0 64 -- which is the base case for f
= 64
Now to your question of using single letter function names - that's the kind of thing you have to get used to it is a way most people in the community write. It has no effect on the compiler how you name your functions - as long as they start with a lower case letter.
As others noted, the function is written using tail-recursion for efficiency.
However, note that one could remove the innermost where while preserving tail-recursion as follows: instead of
x ^ n | n > 0 = f x (n-1) x
where f _ 0 y = y
f x n y = g x n
where g x n | even n = g (x*x) (n `quot` 2)
| otherwise = f x (n-1) (x*y)
we can use
x ^ n | n > 0 = f x (n-1) x
where f _ 0 y = y
f x n y | even n = f (x*x) (n `quot` 2) y
| otherwise = f x (n-1) (x*y)
which is also arguably more readable.
I have however no idea why the authors of the Prelude chose their variant.