Assigning special cases when certain variables have certain values? - haskell

for my functional programming homework I am instructed to write a function that gives back the real solutions of a quadratic equation in a list, I used the discriminant to find them out.
So, my code looks something like this:
quadSols::Double->Double->Double->[Double]
quadSols a b c = [x1,x2]
where
x1 = (-b - sqrt d) / (2 * a)
x2 = (-b + sqrt d) / (2 * a)
d = (b * b) - 4 * a * c
Now, the problem is in the case a = 0, for which the solution would be simply x = -c / b.
I tried something like this, it sounds completely wrong but I don't really know what to do.
if a == 0 then quadSols a b c = [x]
and then added to the "where" part:
x = -c / b
when trying to load it with ghci I get:
parse error on input ‘=’
Failed, modules loaded: none.
Can anyone provide me with some guidance?

You can simply pattern match for the case where a == 0:
quadSols :: Double -> Double-> Double-> [Double]
quadSols 0 b c = [x]
where x = -c / b
quadSols a b c = [x1,x2]
where
x1 = (-b - sqrt d) / (2 * a)
x2 = (-b + sqrt d) / (2 * a)
d = (b * b) - 4 * a * c
Note that you must include the first case before the second, since cases are matched in the order they are declared.

You can add another equation to quadSols:
quadSols 0 b c = [x]
where
x = (-c) / b
quadSols a b c = [x1,x2]
where
…
Or use a guard:
quadSols a b c
| a == 0 = [x]
| otherwise = [x1,x2]
where
x = (-c) / b
…
Due to laziness, the definitions in the where clause won’t be evaluated unless necessary to produce a result.

Related

Beginner to Haskell type system : "Haskell non-type variable argument in constraint" Error

In an attempt to dip my toes in functional programming, I'm attempting to pick up Haskell and running into some mental issues with the type system.
Running the following code gives proper output (e.g. generates coordinates for a circle wrapped around a cylinder of radius R at angle theta):
coilGeneration_AngleTest housingRadius coilWidth coilDepth numEle zoffset centralAngle
= [ (x',y',z)
| theta <- [0,2*pi/(numEle-1)..2*pi]
, let x = housingRadius * cos(coilWidth*cos(theta)/housingRadius)
, let y = housingRadius * sin(coilWidth*cos(theta)/housingRadius)
, let z = coilDepth * sin(theta)+zoffset
, let x' = x * cos(centralAngle) - y * sin(centralAngle)
, let y' = x * sin(centralAngle) + y * cos(centralAngle)
]
Sample coilGeneration_AngleTest function output
However, attempting to generalize this into a function that generates an arbitrary NxM array of circles with varying overlaps in the polar and z-directions by running:
coilArrayGeneration_Test r nE width depth n m mu gam
= [ (x',y',z',i,j)
| theta <- [0,2*pi/(nE-1)..2*pi]
, i <- [1..n]
, j <- [1..m]
, let a = width/2
, let b = depth/2
, let x = r * cos(a*cos(theta)/r)
, let y = r * sin(a*cos(theta)/r)
, let z = b * sin(theta)
, let phi = (2*i-1-n)((a-mu)/r)
, let zo = (2*j-1-m)(b-gam)
, let x' = x * cos(phi) - y * sin(phi)
, let y' = x * sin(phi) + y * cos(phi)
, let z' = z + zo
]
gives the following error:
Build profile: -w ghc-9.2.5 -O1
In order, the following will be built (use -v for more details):
- Haskell-0.1.0.0 (exe:Haskell) (file app/Main.hs changed)
Preprocessing executable 'Haskell' for Haskell-0.1.0.0..
Building executable 'Haskell' for Haskell-0.1.0.0..
[1 of 1] Compiling Main ( app/Main.hs, /Users/zack/Desktop/Udemy/Haskell/dist-newstyle/build/aarch64-osx/ghc-9.2.5/Haskell-0.1.0.0/x/Haskell/build/Haskell/Haskell-tmp/Main.o )
app/Main.hs:66:1: error:
• Non type-variable argument in the constraint: Num (c -> c)
(Use FlexibleContexts to permit this)
• When checking the inferred type
coilArrayGeneration_Test :: forall {c}.
(Floating c, Num (c -> c), Enum c, Enum (c -> c)) =>
c
-> c
-> c
-> c
-> (c -> c)
-> (c -> c)
-> c
-> c
-> [(c, c, c, c -> c, c -> c)]
|
66 | coilArrayGeneration_Test r nE width depth n m mu gam = [(x',y',z',i,j)|theta <- [0,2*pi/(nE-1)..2*pi],....
Failure Output
After googling for a while, it seemed that my function had an improper type implied by the compiler but I unfortunately don't understand the idea Haskell Type Definition well enough to fix it. I attempted to define the types the way I see them, namely:
r -> Double
nE -> Int
width -> Double
depth -> Double
n -> Int
m -> Int
mu -> Double
gam -> Double
x' -> Double
y' -> Double
z' -> Double
I -> Int
j -> Int
Getting:
coilArrayGeneration_Test :: (Floating a, Integral b) => a -> b -> a -> a -> b -> b -> a -> a -> [(a,a,a,b,b)]
coilArrayGeneration_Test r nE width depth n m mu gam
= [ (x',y',z',i,j)
| theta <- [0,2*pi/(nE-1)..2*pi]
, i <- [1..n]
, j <- [1..m]
, let a = width/2
, let b = depth/2
, let x = r * cos(a*cos(theta)/r)
, let y = r * sin(a*cos(theta)/r)
, let z = b * sin(theta)
, let phi = (2*i-1-n)((a-mu)/r)
, let zo = (2*j-1-m)(b-gam)
, let x' = x * cos(phi) - y * sin(phi)
, let y' = x * sin(phi) + y * cos(phi)
, let z' = z + zo
]
But this threw a whole host of errors:
Errors after Type Declaration
Which clearly means I don't know what I'm doing and mucked up the type declarations somehow.
Can anyone steer me the right way?
When you see a compiler error involving something like Num (c -> c), it never has anything to do with -XFlexibleContexts or with incorrect inferred types. It simply means you attempted to use something as a function which is not a function.
“Use as a function” entails simply that you have some expression of the form f x, where f and x can be arbitrary subexpressions. This includes in particular also expressions like (1+2)(3+4), which is the same as
let f = 1 + 2
x = 3 + 4
in f x
Presumably you meant to express multiplication by the juxtaposition. Well, use the multiplication operator then! I.e. (1+2)*(3+4).
Your code has also another problem: you trying to use the index variables in real-valued expression. Unlike the missing multiplication operators, this is fairly sensible, but Haskell doesn't allow this either. You need to explicitly wrap the integrals in fromIntegral.
coilArrayGeneration_Test r nE width depth n m μ γ
= [ (x',y',z',i,j)
| ϑ <- [0, 2*pi/fromIntegral(nE-1) .. 2*pi]
, i <- [1..n]
, j <- [1..m]
, let a = width/2
b = depth/2
x = r * cos(a*cos ϑ/r)
y = r * sin(a*cos ϑ/r)
z = b * sin ϑ
φ = fromIntegral(2*i-1-n) * ((a-μ)/r)
z₀ = fromIntegral(2*j-1-m) * (b-γ)
x' = x * cos φ - y * sin φ
y' = x * sin φ + y * cos φ
z' = z + z₀
]
I would strongly recommend you refactor this a bit, both code and types. 5-tuples are very obscure, you should at least wrap x,y,z in a suitable vector type.

How to create a function that generates an infinite list of an integer-sequence that is defined recursively with two initial numbers X_0 and X_1

Let's say I have the recursive definition for the following sequence of integers: a_0 = 5, a_n = 2a_0+3 -> 5,13,29,61,125...
I want to use the iterate function in Haskell to generate an infinite list of this sequence. To do that I could write the following code:
intSequence :: Integer -> Integer -> [Integer]
intSequence a0 m = iterate nextNum a0
where nextNum a = 2*a + m
ghci> let an = intSequence 5 3
ghci> take 5 a
[5,13,29,61,125]
Now let's say I instead have the following:
X_n = X_n-1 * m_1 + X_n-2 * m_2 + a
Now I want to create a function called in the following way:
intSequence x0 x1 m1 m2 a
that returns an infinite list of a sequence that adheres to the rules of the definition above.
For example: For parameters X0=1, X1=2, m1=2, m2=0, a=0 we get Xn=X_n-1 * 2 + X_n-2 * 0 + 0 = X_n-1 * 2 which gives us [1,2,4,8,16,...]
Another example: For parameters X0=0, X1=1, m1=1, m2=1, a=0 we get the Fibonacci-sequence X_n = X_n-1 * 1 + X_n-2 * 1 + 0 = X_n-1 + X_n-2 which gives us [0,1,1,2,3,5,8,...]
How can I implement this intSequence function using iterate?
I tried the following which does not work as intended:
intSequence :: Integer -> Integer -> Integer -> Integer -> Integer -> [Integer]
intSequence x0 x1 m1 m2 a = x0:x1:iterate (nextNum x0) x1
where
nextNum x0' x1' = x1'*m1 + x0'*m2 + a
ghci> a = intSequence 0 1 1 1 0
ghci> take 10 a
[0,1,1,1,1,1,1,1,1,1]
Which obviously is incorrect and logically so as I never change what x0 and x1 are. I think I need to use recursion somehow but I just can't figure out how. Should I maybe not use iterate at all?
This is much easier to do with recursion:
-- helper function for recursion
intSequence' :: (Integral a) => (a, a) -> a -> a -> a -> [a]
-- p2 is X_n-2 and p1 is X_n-1
intSequence' (p2, p1) m1 m2 a =
-- recurse using X_n-1 as new X_n-2 and current term as new X_n-1
cur:intSequence' (p1, cur) m1 m2 a
-- calculate the current term in the sequence
where cur = p1 * m1 + p2 * m2 + a
-- set previous terms correctly and prepend them to the sequence
intSequence :: (Integral a) => a -> a -> a -> a -> a -> [a]
intSequence x0 x1 m1 m2 a = x0:x1:intSequence' (x0, x1) m1 m2 a

Algorithm to calculate exponent using recursion and mod

I was taught a different way to calculate exponents using mod and recursion, but I don't fully understand it. The method is: To do b^e, we can break it down like so:
q = e div 2
r = e mod 2
then e = 2q+r, and r could be 0 or 1.
If r=0:
b^e = (b^q)^2
If r=1:
b^e = (b^q)^2 * b
base case: b^0 = 1.
For example: 2^2, b=2, e=2.
q = 2/2 = 1
r = 2mod2 = 0
r=0, therefore 2^2 = 2^1^2
I am trying to code this.
pow :: Integer -> Integer -> Integer
pow b e
| e == 0 = 1
| r == 0 = pow (pow b q) 2
| r == 1 = b * pow (pow b q) 2
where
(q, r) = divMod e 2
But the code does not end any time when e!=0, for example, pow (-2) 4 or pow 1 1 goes on forever. Any idea why?
If you try evaluating pow b 2 by hand you'll quickly see why. Since divMod 2 2 = (1, 0), we expand from pow b 2 to pow (pow b 1) 2. Note that this is also of the form pow b' 2, with b' = pow b 1. So we just get an infinite chain:
pow b 2
=
pow (pow b 1) 2
=
pow (pow (pow b 1) 1) 2
=
pow (pow (pow (pow b 1) 1) 1) 2
=
...
There's a couple ways to solve it. You could add a base case for e == 2, or instead of recursively calling pow twice you could just do the multiplication yourself (as in replacing pow foo 2 with foo * foo in your existing code).
You also need to provide a base case for when e is 2:
pow b 2 = b * b
Without this, your recursion doesn't end, because it becomes pow (pow b 1) 2 and you don't get anywhere.
As mentioned in the previous answers, your code almost works, and it is just a matter of allowing the recursion to stop.
See the code below for a possible fix. The argument of the recursive call is at most half the current argument, hence the recursion will have to stop.
On a side note, this algorithm is more than 2,000 years old, and originated in ancient India. Please treat it with all due respect :-)
https://mathoverflow.net/questions/107708/origin-of-square-and-multiply-algorithm
pow :: Integer -> Integer -> Integer
pow b e
| e == 0 = 1
| r == 0 = let bpq = pow b q in bpq*bpq
| r == 1 = let bpq = pow b q in bpq*bpq*b
where
(q, r) = divMod e 2
main = do
let b = 3 :: Integer
let e = 7 :: Integer
let x = b^e
putStrLn ("b^e = " ++ show x)
let y = pow b e
putStrLn ("pow b e = " ++ show y)

Haskell numerical integration via Trapezoidal rule results in wrong sign

I've written some code that's meant to integrate a function numerically using the trapezoidal rule. It works, but the answer it produces has a wrong sign. Why might that be?
The code is:
integration :: (Double -> Double) -> Double -> Double -> Double
integration f a b = h * (f a + f b + partial_sum)
where
h = (b - a) / 1000
most_parts = map f (points (1000-1) h)
partial_sum = sum most_parts
points :: Double -> Double -> [Double]
points x1 x2
| x1 <= 0 = []
| otherwise = (x1*x2) : points (x1-1) x2
Trapezoidal rule
The code is probably inelegant, but I'm only a student of Haskell and would like to deal with the current problem first and coding style matters after that.
Note: This answer is written in literate Haskell. Save it with .lhs as extension and load it in GHCi to test the solution.
Finding the culprit
First of all, let's take a look at integration. In its current form, it contains only summation of function values f x. Even though the factors aren't correct at the moment, the overall approach is fine: you evaluate f at the grid points. However, we can use the following function to verify that there's something wrong:
ghci> integration (\x -> if x >= 10 then 1 else (-1)) 10 15
-4.985
Wait a second. x isn't even negative in [10,15]. This suggests that you use the wrong grid points.
Grid points revisited
Even though you've linked the article, let's have a look at an exemplary use of the trapezoidal rule (public domain, original file by Oleg Alexandrov):
Although this doesn't use a uniform grid, let's suppose that the 6 grid points are equidistant with grid distance h = (b - a) / 5. What are the x coordinates of those points?
x_0 = a + 0 * h (== a)
x_1 = a + 1 * h
x_2 = a + 2 * h
x_3 = a + 3 * h
x_4 = a + 4 * h
x_5 = a + 5 * h (== b)
If we use set a = 10 and b = 15 (and therefore h = 1), we should end up with [10, 11, 12, 13, 14, 15]. Let's check your points. In this case, you would use points 5 1 and end up with [5,4,3,2,1].
And there's the error. points doesn't respect the boundary. We can easily fix this by using pointsWithOffset:
> points :: Double -> Double -> [Double]
> points x1 x2
> | x1 <= 0 = []
> | otherwise = (x1*x2) : points (x1-1) x2
>
> pointsWithOffset :: Double -> Double -> Double -> [Double]
> pointsWithOffset x1 x2 offset = map (+offset) (points x1 x2)
That way, we can still use your current points definition to generate grid points from x1 to 0 (almost). If we use integration with pointsWithOffset, we end up with
integration :: (Double -> Double) -> Double -> Double -> Double
integration f a b = h * (f a + f b + partial_sum)
where
h = (b - a) / 1000
most_parts = map f (pointsWithOffset (1000-1) h a)
partial_sum = sum most_parts
Tying up loose ends
However, this doesn't take into account that you use all inner points twice in the trapezoid rule. If we add the factors, we end up with
> integration :: (Double -> Double) -> Double -> Double -> Double
> integration f a b =
> h / 2 * (f a + f b + 2 * partial_sum)
> -- ^^^ ^^^
> where
> h = (b - a) / 1000
> most_parts = map f (pointsWithOffset (1000-1) h a)
> partial_sum = sum most_parts
Which yields the correct value for our test function above.
Exercise
Your current version only supports 1000 grid points. Add an Int argument so that one can change the number of grid points:
integration :: Int -> (Double -> Double) -> Double -> Double -> Double
integration n f a b = -- ...
Furthermore, try to write points in different ways, for example go from a to b, use takeWhile and iterate, or even a list comprehension.
Yes it indeed was the points plus you had some factors wrong (the inner points are multiplied by 2) - this is the fixed version of your code:
integration :: (Double -> Double) -> Double -> Double -> Double
integration f a b = h * (f a + f b + innerSum) / 2
where
h = (b - a) / 1000
innerPts = map ((2*) . f . (a+)) (points (1000-1) h)
innerSum = sum innerPts
points :: Double -> Double -> [Double]
points i x
| i <= 0 = []
| otherwise = (i*x) : points (i-1) x
which gives sensible approximations (to 1000 points):
λ> integration (const 2) 1 2
2.0
λ> integration id 1 2
1.5
λ> integration (\x -> x*x) 1 2
2.3333334999999975
λ> 7/3
2.3333333333333335

Haskell take sum recursively

Hello I want to take a sum of functions call in Haskel but I cannot figure out what I am doing wrong. To be more specific, I have a function f(a,b,c)=a+b+c and I want to take an int like this:
x=Sum( from i=0 to i=c) f(1,1,i)
so far I have written this, but it doesn't even compile. Can you help me?
f a b c = a+b+c
my_sum f a b c+1 =f a b c+1 + my_sum f a b c
I get parse error in pattern my_sum
eg for my_sum f 1 1 5 the result would be f(1,1,5)+f(1,1,4)+f(1,1,3)+f(1,1,2)+f(1,1,1)
I dont want to use lists
n+k patterns are bad
Your code:
my_sum f a b c+1 =f a b c+1 + my_sum f a b c
includes a pattern in the form c+1 which A) should have parentheses B) Needs a base case (I assume you want to stop when c == 0) and C) is a syntactic form that has been removed from the language.
Instead, explicitly subtract 1 from c when you want and be sure to handle the base case:
my_sum f a b 0 = f a b 0
my_sum f a b n = f a b n + my_sum f a b (n-1)
This also has a memory leak meaning it will build up a large computation in the form f1 + (f a b n' + (f a b n'' + (f a b n''' + (.... You can handle the leak by using an accumulator or a higher level function and optimization at compile-time.
A cleaner Solution
List comprehension strikes me as the most reasonable solution here:
sum [f a b i | i <- [0..c] ]
The sum of the function f applied to arugments a, b and finally i where i ranges from 0 to c inclusively.
You can't have the c+1 on the left side of a definition. Since you're just summing, it doesn't matter if you count up from 0 to c or count down from c to 0, so you could instead do
my_sum f a b 0 = f a b 0
my_sum f a b c = f a b c + my_sum f a b (c - 1)
Then you could use it as
> let g x y z = x + y + z
> my_sum g 0 0 10
55
Some more detail on why your code failed to compile: Whenever you have a pattern on the left side of a definition, such as
fib 0 = 1
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)
You can only match on constructors, names (like n or c), and literals (which are essentially constructors for the basic types). The function + is not a constructor, it is a function belonging to the Num typeclass, so therefore you can not pattern match on it. You may be confused from seeing list pattern matching before because it uses an operator:
myListSum [] = 0
myListSum (x:xs) = x + myListSum xs
but in fact, : is the Cons constructor for lists, and [] is the empty list constructor. You can think of the list type defined as
data [a] = [] | a : [a]
Or, if you were to replace all the symbols with words
data List a = Empty | Cons a (List a)
although its a bit different in reality since there's more that goes into defining lists, but that's the basic idea. This means that a pattern like
f [] = ...
f (x:xs) = ...
Is equivalent to
f Empty = ...
f (Cons x xs) = ...
just with more convenient syntax.
However, Int can be though of as a very large ADT defined as
data Int = -2147483648 | -2147483647 | ... | -1 | 0 | 1 | ... | 2147483646 | 2147483647
where each number itself is a different constructor. Then you can match on any individual number, but not anything like (x + 1) or (x * 2), because + and * are not constructors, just regular functions. (Note: Int is not actually defined this way because that would be really inefficient, it's defined at a more primitive level)
You can get from list formulations to the non-list, recursive formulations, with manual inlining and fusing of the functions in play:
{-# LANGUAGE BangPatterns #-}
import Data.List
f a b c = a+b+c
g f a b c = sum . map (f a b) $ [0..c]
= foldl' (\ !x y -> x + f a b y) 0 $ enumFromTo 0 c
= h 0 0 where
h !acc i | i > c = acc
| otherwise = h (acc + f a b i) (i+1)
Strictness annotations prevent uncontrolled build-up of thunks and stack overflow for big values of c.

Resources