Pattern matching on Ints - function

I am a beginner in learning Haskell, and I wanted to know if you could pattern match on Ints like so:
add x 0 = x
add x (1 + y) = 1 + x + add x y,
Or maybe in this way:
add x 0 = x
add x (successor y) = 1 + x + add x y

There is an extension that lets you do that, but instead you should simply pattern match on y, and subtract 1 manually:
add x y = 1 + x + add x (y - 1)
The extension is called NPlusKPatterns. If you really want to use it (keep in mind it's deprecated in haskell 2010), it can be enabled by either passing a -XNPlusKPatterns parameter to GHC, or putting a {-# LANGUAGE NPlusKPatterns #-} at the top of your file.

Pattern matching isn't arbitrary case analysis. It's a disciplined, but limited form of case analysis, where the cases are the constructors of a data type.
In the specific case of pattern matching integers, the constructors are taken to be the integer values. So you can use integer values as the cases for pattern-matching:
foo 0 = ...
foo 2 = ...
foo x = ...
But you can't use arbitrary expressions. The following code is illegal:
foo (2 * x) = ...
foo (2 * x + 1) = ...
You may know that ever integer is either of the form 2 * x or 2 * x + 1. But the type system doesn't know.

The formatting of your code is a bit off so it is difficult to know what you're asking but you can using pattern matching for input of type Int. An example would be
add x 0 = x
add x y = x + y

Related

Matlab - Undefined function 'int_f_1' for input arguments of type 'double'

Currently, I am working on a program that integrates x + x^2 + e^x + 2cos(x/2) - 1 with three input variables, a, b, and n. What I need returned is the numerical integral from a to b with n increments. The function also has to return trapezoids for each n as a column vector. Thus, the integral value as a scalar, and a vector of values.
I've gotten to a point where the function int_f_1 is undefined for some reason, and I have no idea why. I thought by nesting that function under the test function, it would help. But it does not, and I don't know why that is. Any suggestions?
function [y] = test_function_1(x);
y = x + x.^2 + exp(x) + 2*cos(x/2) - 1
end
function [int_f, increment] = int_f_1 (a, b, n);
f = #test_function_1;
h = a + b ./ n
increments = h
int_f = integral(h, f)
end

How does Unison compute the hashes of recursive functions?

In Unison, functions are identified by the hashes of their ASTs instead of by their names.
Their documentation and their FAQs have given some explanations of the mechanism.
However, the example presented in the link is not clear to me how the hashing actually works:
They used an example
f x = g (x - 1)
g x = f (x / 2)
which in the first step of their hashing is converted to the following:
$0 =
f x = $0 (x - 1)
g x = $0 (x / 2)
Doesn't this lose information about the definitions.
For the two following recursively-defined functions, how can the hashing distinguish them:
# definition 1
f x = g (x / 2)
g x = h (x + 1)
h x = f (x * 2 - 7)
# definition 2
f x = h (x / 2)
g x = f (x + 1)
h x = g (x * 2 - 7)
In my understanding, brutally converting all calling of f g and h to $0 would make the two definitions undistinguishable from each other. What am I missing?
The answer is that the form in the example (with $0) is not quite accurate. But in short, there's a special kind of hash (a "cycle hash") which is has the form #h.n where h is the hash of all the mutually recursive definitions taken together, and n is a number from 0 to the number of terms in the cycle. Each definition in the cycle gets the same hash, plus an index.
The long answer:
Upon seeing cyclical definitions, Unison captures them in a binding form called Cycle. It's a bit like a lambda, but introduces one bound variable for each definition in the cycle. References within the cycle are then replaced with those variables. So:
f x = g (x - 1)
g x = f (x / 2)
Internally becomes more like (this is not valid Unison syntax):
$0 = Cycle f g ->
letrec
[ x -> g (x - 1)
, x -> f (x / 2) ]
It then hashes each of the lambdas inside the letrec and sorts them by that hash to get a canonical order. Then the whole cycle is hashed. Then these "cycle hashes" of the form #h.n get introduced at the top level for each lambda (where h is the hash of the whole cycle and n is the canonical index of each term), and the bound variables get replaced with the cycle hashes:
#h.0 = x -> #h.1 (x - 1)
#h.1 = x -> #h.0 (x / 2)
f = #h.0
g = #h.1

Benefits of where notation in Haskell

What are the pros and cons of explicit function definition as opposed to where notation in Haskell?
Explicit function definition:
foo :: Integer -> Integer
foo a = bar a
where
bar :: Integer -> Integer
bar a = Some code here
as opposed to:
foo :: Integer -> Integer
foo a = bar a
bar :: Integer -> Integer
bar a = Some code here
Why would I use one over the other? Is there anything to be aware of with regards to efficiency? Security? Code reusability? Code readability?
If your auxiliary function is not going to be used anywhere else, it's better not to pollute the namespace and use a local definition.
When your outer function has only one top-level "pattern", the where clause can simplify the definition of the auxiliary function because the parameters of the outer function will be in scope.
outer x v z f = undefined
where
inner i = i + x + v + z + f
versus
outer x v z f = undefined
inner x v z f i = i + x + v + z + f
If your function has more than one top-level "pattern", then you can't share bindings across patters using where. You have to define a top-level binding.
Certain ways of using where can incur in non-obvious performance penalties. This definition (taken from the HaskellWiki article on let vs where)
fib x = map fib' [0 ..] !! x
where
fib' 0 = 0
fib' 1 = 1
fib' n = fib (n - 1) + fib (n - 2)
is slower than this one:
fib = (map fib' [0 ..] !!)
where
fib' 0 = 0
fib' 1 = 1
fib' n = fib (n - 1) + fib (n - 2)
and also slower than defining fib' at the top-level.
The reason is that, in the first definition, a new fib' is created for each invocation of fib. Explained here.
If you need bar only in the scope of foo, it is more readable and better information hiding to declare it in "where". If bar should be reusable outside of foo, the it needs to be declared parallel to foo.

How can I prove the correctness of the following algorithm?

Consider the following algorithm min which takes lists x,y as parameters and returns the zth smallest element in union of x and y.
Pre conditions: X and Y are sorted lists of ints in increasing order and they are disjoint.
Notice that its pseudo code, so indexing starts with 1 not 0.
Min(x,y,z):
if z = 1:
return(min(x[1]; y[1]))
if z = 2:
if x[1] < y[1]:
return(min(x[2],y[1]))
else:
return(min(x[1], y[2]))
q = Ceiling(z/2) //round up z/2
if x[q] < y[z-q + 1]:
return(Min(x[q:z], y[1:(z - q + 1)], (z-q +1)))
else:
return(Min(x[1:q], B[(z -q + 1):z], q))
I can prove that it terminates, because z keeps decreasing by 2 and will eventually reach one of the base cases but I cant prove the partial correctness.
Your code is not correct.
Consider the following input:
x = [0,1]
y = [2]
z = 3
You then get q = 2 and, in the if clause that follows, access y[z-q+1], i.e. y[2]. This is an array bounds violation.

Math - Get x & y coordinates at intervals along a line

I'm trying to get x and y coordinates for points along a line (segment) at even intervals. In my test case, it's every 16 pixels, but the idea is to do it programmatically in ActionScript-3.
I know how to get slope between two points, the y intercept of a line, and a2 + b2 = c2, I just can't recall / figure out how to use slope or angle to get a and b (x and y) given c.
Does anyone know a mathematical formula to figure out a and b given c, y-intercept and slope (or angle)? (AS3 is also fine.)
You have a triangle:
|\ a^2 + b^2 = c^2 = 16^2 = 256
| \
| \ c a = sqrt(256 - b^2)
a | \ b = sqrt(256 - a^2)
| \
|__________\
b
You also know (m is slope):
a/b = m
a = m*b
From your original triangle:
m*b = a = sqrt(256 - b^2)
m^2 * b^2 = 256 - b^2
Also, since m = c, you can say:
m^2 * b^2 = m^2 - b^2
(m^2 + 1) * b^2 = m^2
Therefore:
b = m / sqrt(m^2 + 1)
I'm lazy so you can find a yourself: a = sqrt(m^2 - b^2)
Let s be the slop.
we have: 1) s^2 = a^2/b^2 ==> a^2 = s^2 * b^2
and: 2) a^2 + b^2 = c^2 = 16*16
substitute a^2 in 2) with 1):
b = 16/sqrt(s^2+1)
and
a = sqrt((s^2 * 256)/(s^2 + 1)) = 16*abs(s)/sqrt(s^2+1)
In above, I assume you want to get the length of a and b. In reality, your s is a signed value, so a could be negative. Therefore, the incremental value of a will really be:
a = 16s/sqrt(s^2+1)
The Point class built in to Flash has a wonderful set of methods for doing exactly what you want. Define the line using two points and you can use the "interpolate" method to get points further down the line automatically, without any of the trigonometry.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/geom/Point.html#interpolate()
The Slope is dy/dx. Or in your terms A/B.
Therefore you can step along the line by adding A to the Y coordinate, and B to the X coordinate. You can Scale A and B to make the steps bigger or smaller.
To Calculate the slope and get A and B.
Take two points on the line (X1,Y1) , (X2,Y2)
A= (Y2-Y1)
B= (X2-X1)
If you calculate this with the two points you want to iterate between simply divide A and B by the number of steps you want to take
STEPS=10
yStep= A/STEPS
xStep= B/STEPS
for (i=0;i<STEPS;i++)
{
xCur=x1+xStep*i;
yCur=y1+yStep*i;
}
Given the equation for a line as y=slope*x+intercept, you can simply plug in the x-values and read back the y's.
Your problem is computing the step-size along the x-axis (how big a change in x results from a 16-pixel move along the line, which is b in your included plot). Given that you know a^2 + b^2 = 16 (by definition) and slope = a/b, you can compute this:
slope = a/b => a = b * slope [multiply both sides by b]
a^2 + b^2 = 16 => (b * slope)^2 + b^2 = 16 [by substitution from the previous step]
I'll leave it to you to solve for b. After you have b you can compute (x,y) values by:
for x = 0; x += b
y = slope * x + intercept
echo (x,y)
loop