Implementing Extended Euclidean algorithm - function

I want to make a function combine which given two integers n and m, returns a triple of integers
(a, b, gcd(n, m)) such that:
am + bn = gcd(n, m)
Should not assume that the integers will always be positive.
gcd :: Int -> Int -> Int
gcd n m
| n == m = n
| n > m = gcd (n-m) m
| n < m = gcd n (m-n)
combine :: Int ->Int -> (Int,Int,Int)
x1=1; y1=0; x2=0; y2=1
while ( m /=0 )
( q=div n m ; r=mod n m ; n=m ; m=r
t=x2 ; x2=x1-q*x2 ; x1=t
t=y2 ; y2=y1-q*y2 ; y1=t )
combine n m = (x1,y1,gcd(n,m))
You will find a screen capture picture link. Click me---> ![link] http://prikachi.com/images.php?images/238/8749238o.png Please if someone have a solution and have idea what I could replace to create the function, would be much appreciated.
Test for the function: combine 3 2 should give this result => (1,-1,1)

I think you might be looking for something like this:
combine :: Int ->Int -> (Int,Int,Int)
combine n m = (x1, y1, gcd n m) where
(x1, y1) = gcdext n m
gcdext :: Int -> Int -> (Int, Int)
gcdext n m = gcdexthelper n m 1 0 0 1 where
gcdexthelper n m x1 y1 x2 y2
| m == 0 = (x1, y1)
| otherwise = gcdexthelper m r x1p y1p x2p y2p where
q = div n m
r = mod n m
x1p = x2
y1p = y2
x2p = x1 - q * x2
y2p = y1 - q * y2
You can of course implement the same with a while loop, but I believe recursion is much more readable in Haskell, so I used it here.
And by the way, GCD is a standard library function in Haskell, so no need to write your own.

Related

How to define a function with Church numerals in lambda-terms?

How can I express the following function by a lambda term?
f(n) = T if n != 0.
F if n = 0.
n stands for a Church numeral.
I know that 0 := λf.λx.x where λx.x is the identity function and all other natural numbers can be expressed by n := λf.λx.f (f ... (f x)) which contains f n times more than the 0-term. E.g. 3 := λf.λx.f (f (f x)).
But how can I derive a valid λ-term for the function above? I think I need a y too for getting the T/F. Therefore I can express the number n by λf.(λxy.fxy), right? But what about the F and T? Is the following a right λ-term for the function above? λf.(λxy.fxy(yFT)) where T=λxy.x and F=λxy.y?
No, you're given the term for n. It is a function that expects two arguments, an f and a z:
isZero n = n ( ;; f, a function, expecting x
;; or the result of (f (f ... (f x) ...))
λx.
;; but we know what we want it to return, always: it is:
F ;; false, for n is _not_ 0
)
( ;; the initial x, in case n is ......... 0!
;; so we know what we want it to be, in case n is 0:
T ;; true, for n _is_ 0
)
and thus
isZero = λn.n(λx.F)T
If n was 0, isZero n will return T; and otherwise, F:
{0}(λx.F)T = T
{1}(λx.F)T = (λx.F)T = F
{2}(λx.F)T = (λx.F)((λx.F)T) = F
{3}(λx.F)T = (λx.F)((λx.F)((λx.F)T)) = F
....

What is the Haskell reverse function expected in this code?

I'm writing a small Haskell exercise, it is should shift some elements within a list, similar to a Caesar cipher, the code is already working, the code is below.
module Lib (shift, cipherEncode, cipherDecode ) where
import Data.Char
import Data.List
import Data.Maybe
abcdata :: [Char]
abcdata = ['a','b','c','d','e','f','g']
iabcdata :: [Char]
iabcdata = ['g','f','e','d','c','b','a']
shift :: Char -> Int -> Char
shift l n = if (n >= 0)
then normalShift l n
else inverseShift l (abs n)
normalShift :: Char -> Int -> Char
normalShift l n = shifter l n abcdata
inverseShift :: Char -> Int -> Char
inverseShift l n = shifter l n reverse(abcdata) -- This is the line
charIdx :: Char -> [Char] -> Int
charIdx target xs = fromJust $ elemIndex target xs
shifter :: Char -> Int -> [Char] -> Char
shifter l n xs = if (n < length (xs))
then
picker ((charIdx l xs) + n) xs
else
picker ((charIdx l xs) + (n `mod` length (xs))) xs
picker :: Int -> [Char] -> Char
picker n xs = if n < length xs
then
xs!!n
else
xs!!(n `mod` length (xs))
The question I have is regarding the line
inverseShift l n = shifter l n reverse(abcdata)
If I change it by
inverseShift l n = shifter l n iabcdata
it works fine
also, when I do reverse(abcdata) == iabcdata it is True
but when I leave the reverse in the code I get the following error
* Couldn't match expected type `[Char] -> Char'
with actual type `Char'
* The function `shifter' is applied to four arguments,
but its type `Char -> Int -> [Char] -> Char' has only three
In the expression: shifter l n reverse (abcdata)
In an equation for `inverseShift':
inverseShift l n = shifter l n reverse (abcdata)
|
21 | inverseShift l n = shifter l n reverse(abcdata)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* Couldn't match expected type `[Char]'
with actual type `[a0] -> [a0]'
* Probable cause: `reverse' is applied to too few arguments
What am I doing wrong by calling shifter with reverse(abcdata) ?
That's not how parentheses work in Haskell. The way you wrote it, reverse and abcdata would both be arguments to shifter, but you want abcdata to be an argument to reverse. Do shifter l n (reverse abcdata) instead of shifter l n reverse(abcdata).
What am I doing wrong by calling shifter with reverse(abcdata) ?
The answer is in the message:
* Couldn't match expected type `[Char] -> Char'
with actual type `Char'
* The function `shifter' is applied to four arguments,
but its type `Char -> Int -> [Char] -> Char' has only three
In the expression: shifter l n reverse (abcdata)
In an equation for `inverseShift':
inverseShift l n = shifter l n reverse (abcdata)
Repeat,
In an equation for `inverseShift':
inverseShift l n = shifter l n reverse (abcdata)
~~~~~~~~~~~~~ -- mind the gap!
That is how your expression was read by Haskell. And this is how it was written by you:
|
21 | inverseShift l n = shifter l n reverse(abcdata)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
So you haven't in fact called shifter with reverse(abcdata).
You called it with reverse and (abcdata) (as well l and n), as is also explained in the other answer.

How can you write a function that takes 'm' and 'n' then multiplies 'm', 'n' number of times?

Here is the problem: Declare type and define a function that takes 2 positive numbers (say m and n) as input, and raise m to the power of n. please use recursion only. Don’t use power operator or library function, just use recursion.
this is my code so far:
sqr :: Int -> Int -> Int
sqr m n
| m > 0 && n > 0 = sqr (m * m) (n - 1)
| otherwise = m
For some reason, when I do sqr 10 2, it gives me like 1000 or something. Does anyone know what I'm doing wrong?
Let's expand. Also, your function should be called pow, not sqr, but that is not really important.
sqr 10 2 = sqr (10 * 10) (2 - 1)
= sqr 100 1
= sqr (100 * 100) (1 - 1)
= sqr 10000 0
= 10000
This demonstrates why sqr 10 2 = 10000.
Every time you recurse, there's a different value for m. So you need to take that into account some way:
Either you write a version that works even though m has a different value each time, or,
You find a way to keep the original value of m around.
I would say that the simplest method uses the fact that m^n = m * m^(n-1), and m^0 = 1.
If you're clever, there's a method that's much faster, which also relies on the fact that m^2n = (m^n)^2.
Spoilers
Some of those mathematical formulas I wrote above are actually valid Haskell code.
import Prelude hiding ((^))
infixr 8 ^
(^) :: Int -> Int -> Int
-- Do these two lines look familiar?
m^0 = 1
m^n = m * m^(n-1)
This is just the infix version of the function. You can change the infix operator to a normal function,
pow :: Int -> Int -> Int
pow m 0 = 1
pow m n = m * pow m (n - 1)
And the faster version:
pow :: Int -> Int -> Int
pow m 0 = 1
pow m n
| even n = x * x where x = pow m (n `quot` 2)
| otherwise = m * pow m (n - 1)
There are 2 separate problems here. Just write out all the term-rewriting steps to see what they are:
sqr 10 2
sqr (10 * 10) (2 - 1)
sqr 100 (2 - 1)
sqr 100 1
sqr (100 * 100) (1 - 1)
sqr 10000 (1 - 1)
sqr 10000 0
10000
This will show you one of the problems clearly. If you don't see the other one yet, try starting with
sqr 10 3

How to let OCaml function returns a tuple containing a string and a function?

Eventually what I want is what x represents:
let x = (something, (myfunc1 para1));;
so that when calling x, I get a tuple, but when calling (snd x) para, I will get a return value of myfunc1 para.
What I'm trying is like this:
let myfunc2 para1 para2 =
let myfunc1 para2 = ... in
( (fst para1), (myfunc1 para2) );;
And I want to call myfunc2 like this:
let x = myfunc2 para1 to get what I described above. However, what I get is just a function which when called with para1 will return a regular tuple, not a (something, function) tuple
You have a useless para2 parameter in your definition. The correct way is:
let myfunc2 para1 =
let x = ... in
let myfunc1 para2 = ... in
( x, myfunc1 );;
But it would help if we could speak about a concrete example. You are misunderstanding something obvious, but I do not know what.
Here is a concrete example. Suppose we want a function f which accepts a number n and returns a pair (m, g) where m is the square of n and g is a function which adds n to its argument:
let f n =
let m = n * n in
let g k = n + k in
(m, g)
Or shorter:
let f n = (n * n, fun k => n + k)
Now to use this, we can do:
let x = f 10 ;;
fst x ;; (* gives 100 *)
snd x ;; (* gives <fun> *)
snd x 5 ;; (* gives 15, and is the same thing as (snd x) 5 *)
Now let us consider the following bad solution in which we make the kind of mistake you have made:
let f_bad n k =
let m = n * n in
let g k = n + k in
(m, g k)
Now f_bad wants two arguments. If we give it just one, we will not get a pair but a function expecting the other argument. And when we give it that argument, it will return a pair of two integers because (m, g k) means "make a pair whose first component is the integer m and the second component is g applied to k, so that is an integer, too."
Another point worth making is that you are confusing yourself by calling two different things para2. In our definition of f_bad we also confuse ourselves by calling two different things k. The k appearing in the definition of g is not the same as the other k. It is better to call the two k's different things:
let f_bad n k1 =
let m = n * n in
let g k2 = n + k2 in
(m, g k1)
Now, does that help clear up the confusion?

How to create a Prouhet–Thue–Morse sequence in Haskell?

I'm a noob in Haskell, but some experience with ActionScript 3.0 Object Orientated. Thus working on a major programming transition. I've read the basic knowledge about Haskel, like arithmetics. And I can write simple functions.
As a practical assignment I have to generate the Thue-Morse sequence called tms1 by computer in Haskell. So it should be like this:
>tms1 0
0
>tms1 1
1
>tms1 2
10
>tms1 3
1001
>tms1 4
10010110
and so on... According to wikipedia I should use the formula.
t0 = 0
t2n = tn
t2n + 1 = 1 − tn
I have no idea how I can implement this formula in Haskell. Can you guide me to create one?
This is what I got so far:
module ThueMorse where
tms1 :: Int -> Int
tms1 0 = 0
tms1 1 = 1
tms1 2 = 10
tms1 3 = 1001
tms1 x = tms1 ((x-1)) --if x = 4 the output will be 1001, i don't know how to make this in a recursion function
I did some research on the internet and found this code.
Source:
http://pastebin.com/Humyf6Kp
Code:
module ThueMorse where
tms1 :: [Int]
tms1 = buildtms1 [0] 1
where buildtms1 x n
|(n `rem` 2 == 0) = buildtms1 (x++[(x !! (n `div` 2))]) (n+1)
|(n `rem` 2 == 1) = buildtms1 (x++[1- (x !! ((n-1) `div` 2))]) (n+1)
custinv [] = []
custinv x = (1-head x):(custinv (tail x))
tms3 :: [Int]
tms3 = buildtms3 [0] 1
where buildtms3 x n = buildtms3 (x++(custinv x)) (n*2)
intToBinary :: Int -> [Bool]
intToBinary n | (n==0) = []
| (n `rem` 2 ==0) = intToBinary (n `div` 2) ++ [False]
| (n `rem` 2 ==1) = intToBinary (n `div` 2) ++ [True]
amountTrue :: [Bool] -> Int
amountTrue [] = 0
amountTrue (x:xs) | (x==True) = 1+amountTrue(xs)
| (x==False) = amountTrue(xs)
tms4 :: [Int]
tms4= buildtms4 0
where buildtms4 n
|(amountTrue (intToBinary n) `rem` 2 ==0) = 0:(buildtms4 (n+1))
|(amountTrue (intToBinary n) `rem` 2 ==1) = 1:(buildtms4 (n+1))
But this code doesn't give the desired result. Any help is well appreciated.
I would suggest using a list of booleans for your code; then you don't need to explicitly convert the numbers. I use the sequence defined like this:
0
01
0110
01101001
0110100110010110
01101001100101101001011001101001
...
Notice that the leading zeros are quite important!
A recursive definition is now easy:
morse = [False] : map step morse where step a = a ++ map not a
This works because we never access an element that is not yet defined. Printing the list is left as an excercise to the reader.
Here is another definition, using the fact that one can get the next step by replacing 1 with 10 and 0 with 01:
morse = [False] : map (concatMap step) morse where step x = [x,not x]
Edit
Here are easier definitions by sdcvvc using the function iterate. iterate f x returns a list of repeated applications of f to x, starting with no application:
iterate f x = [x,f x,f (f x),f (f (f x)),...]
And here are the definitions:
morse = iterate (\a -> a ++ map not a) [False]
morse = iterate (>>= \x -> [x,not x]) [False]
Your definition of the sequence seems to be as a sequence of bit sequences:
0 1 10 1001 10010110 ... etc.
t0 t1 t2 t3 t4
but the wikipedia page defines it as a single bit sequence:
0 1 1 0 1 ... etc
t0 t1 t2 t3 t4
This is the formulation that the definitions in Wikipedia refer to. With this knowledge, the definition of the recurrence relation that you mentioned is easier to understand:
t0 = 0
t2n = tn
t2n + 1 = 1 − tn
In English, this can be stated as:
The zeroth bit is zero.
For an even, non-zero index, the bit is the same as the bit at half the index.
For an odd index, the bit is 1 minus the bit at half the (index minus one).
The tricky part is going from subscripts 2n and 2n+1 to odd and even, and understanding what n means in each case. Once that is done, it is straightforward to write a function that computes the *n*th bit of the sequence:
lookupMorse :: Int -> Int
lookupMorse 0 = 0;
lookupMorse n | even n = lookupMorse (div n 2)
| otherwise = 1 - lookupMorse (div (n-1) 2)
If you want the whole sequence, map lookupMorse over the non-negative integers:
morse :: [Int]
morse = map lookupMorse [0..]
This is the infinite Thue-Morse sequence. To show it, take a few of them, turn them into strings, and concatenate the resulting sequence:
>concatMap show $ take 10 morse
"0110100110"
Finally, if you want to use the "sequence of bit sequences" definition, you need to first drop some bits from the sequence, and then take some. The number to drop is the same as the number to take, except for the zero-index case:
lookupMorseAlternate :: Int -> [Int]
lookupMorseAlternate 0 = take 1 morse
lookupMorseAlternate n = take len $ drop len morse
where
len = 2 ^ (n-1)
This gives rise to the alternative sequence definition:
morseAlternate :: [[Int]]
morseAlternate = map lookupMorseAlternate [0..]
which you can use like this:
>concatMap show $ lookupMorseAlternate 4
"10010110"
>map (concatMap show) $ take 5 morseAlternate
["0", "1", "10", "1001", "10010110"]
Easy like this:
invertList :: [Integer] -> [Integer]
invertList [] = []
invertList (h:t)
|h == 1 = 0:invertList t
|h == 0 = 1:invertList t
|otherwise = error "Wrong Parameters: Should be 0 or 1"
thueMorse :: Integer -> [Integer]
thueMorse 1 = [0]
thueMorse n = thueMorse (n - 1) ++ invertList (thueMorse (n - 1))