I have come across many forums where they state that the language represented by
L={WWR|WR is the reverse of W and W belongs to (0,1)*}
is NOT REGULAR. And it has been proved by pumping lemma as well.
BUT I am able to write a REGULAR EXPRESSION FOR THIS, where I use the same logic as given in this link.
CHECK THIS:
(0+1) * 11 (0+1) * + (0+1) * 00 (0+1) *
Is there any flaw in logic? Or something that I maybe missing.
Thanks in advance :)
(0+1) * 11 (0+1) * + (0+1) * 00 (0+1) * + (0+1) * initial
= (0+1) * 11 (0+1) * + ((0+1) * 00 (0+1) * + (0+1) *) union is associative
= (0+1) * 11 (0+1) * + (0+1) * L u U = U (U is universe)
= (0+1) * L u U = U (U is universe)
Your regular expression, which contains a union with (0+1)*, is the language which contains all strings of 0s and 1s and contains the target language as a proper subset. Your language contains, among other strings not in the target language, the string 01100.
Note that I am taking + to mean union, juxtaposition to mean concatenation, and * to mean Kleene closure.
Related
Inspired by this question, I have made this code which prints out triangles:
type TriangleMaker = Char -> Int -> [String]
topLeftTriangle :: TriangleMaker
topLeftTriangle c n = [replicate i c | i <- [1 .. n]]
centeredTriangle :: TriangleMaker
centeredTriangle c n = [replicate (n-i) ' ' ++ replicate i c | i <- [0 .. n]]
getType :: IO TriangleMaker
getType = do
let menu = [topLeftTriangle, centeredTriangle]
putStr $ unlines [
"What type of triangle do you want to print? (type 1 and then type the int size)",
"1) Top Left",
"2) Centered"]
line <- getLine
return (menu !! ((read line :: Int) - 1))
trekant :: IO()
trekant = do
triangle <- getType
size <- getLine
putStr $ unlines $ triangle '*' (read size :: Int)
It gives me this output in ghci:
Ok, one module loaded.
ghci> trekant
What type of triangle do you want to print? (type 1 and then type the int size)
1) Top Left
2) Centered
1
6
*
**
***
****
*****
******
ghci> trekant
What type of triangle do you want to print? (type 1 and then type the int size)
1) Top Left
2) Centered
2
6
*
**
***
****
*****
******
I want to make it so that I can use a string as input instead of a char, like so:
trekant :: IO()
trekant = do
triangle <- getType
size <- getLine
putStr $ unlines $ triangle " *" (read size :: Int)
That way, (I think) I'll get a centered triangle as output:
ghci> trekant
What type of triangle do you want to print? (type 1 and then type the int size)
1) Top Left
2) Centered
2
6
*
* *
* * *
* * * *
* * * * *
* * * * * *
Or am I way off here? How can I re-write this so that the triangle is centered?
In case you want to generate a triangle in the center, you should add spaces between two stars, this thus means that the string looks like:
centeredTriangle :: TriangleMaker
centeredTriangle c n = [replicate (n-i) ' ' ++ concat (replicate i [c, ' ']) | i <- [0 .. n]]
We thus generate a string where we have n-i spaces followed by n times the "* " string.
Perhaps it is more elegant to work with intersperse :: a -> [a] -> [a] where we intersperse a list of '*' characters with spaces:
import Data.List(intersperse)
centeredTriangle :: TriangleMaker
centeredTriangle c n = [replicate (n-i) ' ' ++ intersperse ' ' (replicate i c) | i <- [0 .. n]]
This then produces:
ghci> trekant
What type of triangle do you want to print? (type 1 and then type the int size)
1) Top Left
2) Centered
2
6
*
* *
* * *
* * * *
* * * * *
* * * * * *
ghci> trekant
What type of triangle do you want to print? (type 1 and then type the int size)
1) Top Left
2) Centered
2
10
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
I am trying to define a function that computes for any positive integer the square of its factorial
(I am a beginner in Haskell any tips or help is appreciated)
I have tried a couple different ways one i believe to work and one definition i don't understand why it doesn't work
Function i believe works:
squarefact:: Int -> Int
squarefact 0 = 1
squarefact n = n * n * squarefact(n-1)
Function I don't understand why it doesn't work:
squarefact:: Int -> Int
squarefact 0 = 1
squarefact n = (n * squarefact(n-1) ) * (n * squarefact(n-1) )
An explanation and walk through of the dunctions defined would help me understand them better thanks.
The equation
squarefact n = (n * squarefact(n-1) ) * (n * squarefact(n-1) )
could be rewritten in mathematical notation as
(n!)^2 = n * ((n-1)!)^2 * n * ((n-1)!)^2
but this identity is incorrect. The right hand side includes factors 1,2,....,n-1 four times instead of only two, as in the left hand side.
By comparison,
squarefact n = n * n * squarefact(n-1)
is correct, since on both sides all the factors occur exactly twice.
A factorial function can be defined in Haskell as
factorial n = product [1..n]
(where product is a function that calculates the product of all the numbers in a given list.)
Hence,
squarefact n = square (factorial n) =
= square (product [1..n])
= product [1..n] * product [1..n]
= 1 * 2 * 3 * ... * (n-1) * n *
1 * 2 * 3 * ... * (n-1) * n
= product [1..(n-1)] * n * product [1..(n-1)] * n
= n * n * square (product [1..(n-1)])
= n * n * squarefact (n-1)
The equality re-writes break down for n=0 ( squarefact 0 /= 0 * 0 * squarefact (-1) ), so it must be handled as a special case.
I found out this snippet of code which works, but I do not understand why it does. It converts an Int to its representation in binary.
repBinario::Int -> Int
repBinario 0 = 0
repBinario x = 10 * repBinario (x `div` 2) + x `mod` 2
I know what div and mod do. However, how does it place each number that comes from mod together?
In short, it multiplies the accumulated result by 10 on each iteration.
To get a clearer understanding of what's going on we can divide your function into two simpler ones. The first one will convert an integer into a list of binary digits. The other will then do exactly the thing that bothers you: concat a list of binary digits into an integer.
extractBinDigits :: Int -> [Int]
extractBinDigits =
unfoldr (\x -> if x == 0 then Nothing else Just (mod x 2, div x 2))
concatDigits :: [Int] -> Int
concatDigits =
foldr (\a b -> a + b * 10) 0
As you see we simply fold the list multiplying the accumulator by 10 on each step and adding each digit to it.
Then your original function becomes just this:
repBinario :: Int -> Int
repBinario =
concatDigits . extractBinDigits
Division now lets us inspect and reuse the finer pieces of our program providing us with greater flexibility. E.g., by adding another simple function you can now convert the integer into a string in one go:
showDigits :: [Int] -> String
showDigits =
reverse . map (chr . (+ 48))
repStringyBinario :: Int -> String
repStringyBinario =
showDigits . extractBinDigits
Let’s go through an example, then:
repBinario 5
Substitute definition of repBinario 5:
10 * repBinario (5 `div` 2) + 5 `mod` 2
Reduce div and mod:
10 * repBinario 2 + 1
^
Here we have produced our first digit, marked with ^.
Substitute definition of repBinario 2:
10 * (10 * repBinario (2 `div` 2) + 2 `mod` 2) + 1
^
Reduce div and mod:
10 * (10 * repBinario 1 + 0) + 1
^ ^
Substitute definition of repBinario 1:
10 * (10 * (10 * repBinario (1 `div` 2) + 1 `mod` 2) + 0) + 1
^ ^
Reduce div and mod:
10 * (10 * (10 * repBinario 0 + 1) + 0) + 1
^ ^ ^
Substitute definition of repBinario 0:
10 * (10 * (10 * 0 + 1) + 0) + 1
^ ^ ^
Reduce:
101
At each step, (`mod` 2) gets the least significant binary digit, and (`div` 2) shifts the number rightward, discarding the digit and passing the rest of the number recursively to divBinario. At the end, we do the opposite process: (+ d) adds the current digit to the result, and (* 10) shifts the number leftward so we can add more digits.
What you get is a decimal number that looks identical to the binary representation of the original input.
If you remove the multiplication by 10, you get popCount, a function that gives you the population count of a number—the number of 1 bits in its binary representation:
popCount 0 = 0
popCount x = popCount (x `div` 2) + x `mod` 2
popCount 5 == 2
I think it would be best to calculate this function for a small value by hand - this is possible since this is a pure function therefore you can replace left hand side with its definition (i.e. right hand side) - the fancy computer science word for this feature is "referential transparency".
repBinario 24 = 10 * repBinario (24 `div` 2) + 24 `mod` 2
= 10 * repBinario 12 + 0
= 10 * (10 * repBinario (12 `div` 2) + 12 `mod` 2)
= 100 * repBinario 6 + 0
= 100 * (10 * repBinario (6 `div` 2) + 6 `mod` 2)
= 1000 * repBinario 3 + 0
= 1000 * (10 * repBinario (3 `div` 2) + 3 `mod` 2)
= 10000 * repBinario 1 + 1000 * 1
= 10000 (10 * repBinario (1 `div` 2) + 1 `mod` 2) + 1000
= 10000 (10 * repBinario 0 + 1) + 1000
= 10000 (10 * 0 + 1) + 1000
= 10000 * 1 + 1000
= 11000
in those steps I just evaluated the function by its definition and used the fact that integer-addition/multiplication obey the law of distribution.
Let's say I have a naively implemented function like this:
quadratic a b c = (ans1, ans2)
where
ans1 = ((-b) + sqrt (b * b - 4 * a * c)) / (2 * a)
ans2 = ((-b) - sqrt (b * b - 4 * a * c)) / (2 * a)
There are multiple identical subexpressions. How can I tell without reading core that common subexpression elimination is happening or not and to which parts of this?
Using trace might tell you as demonstrated in this SO question.
import Debug.Trace
quadratic a b c = (ans1, ans2)
where
ans1 = ((-b) + tr1 (sqrt (b * b - 4 * a * c))) / (2 * a)
ans2 = ((-b) - tr2 (sqrt (b * b - 4 * a * c))) / (2 * a)
tr1 = trace "ans1"
tr2 = trace "ans2"
main = print $ quadratic 1 10 3
Compiling this with -O2 or -O3 shows both ans1 and ans2 in the trace output indicating that GHC did not perform the CSE. You get similar
results if you use tr1 in both places.
The Haskell Wiki mentions that GHC only performs CSE in limited
circumstances - (link) - and that you are advised to perform
it yourself if you want to make sure it happens.
I need to write a Haskell program that will generate a diamond output recursively.
Here is some sample output for given input
input : 1
output :
*
* *
*
input : 2
output :
*
* *
*
* *
* * * *
* *
*
* *
*
input : 3
output :
*
* *
*
* *
* * * *
* *
*
* *
*
* *
* * * *
* *
* * * *
* * * * * * * *
* * * *
* *
* * * *
* *
*
* *
*
* *
* * * *
* *
*
* *
*
I wrote following functions:
next 0 = [1,0,1]
next n = map (+3^n) (next (n-1)) ++ next (n-1) ++ map (+3^n) (next (n-1))
lpad n = map (++"*") (zipWith ($) (map (take)(next (n-1))) ((repeat(repeat ' '))))
pretty n = putStrLn $ intercalate "\n" $ lpad n
which gives following outputs:
pretty 1
*
*
*
pretty 2
*
*
*
*
*
*
*
*
*
Can anyone help me with the remaining halves? Thanks in advance.
For n==0, next n describes the whole picture up to mirroring. This is not the case anymore for greater n. So, in a first step, we change the next function to output a symmetric picture:
mmap = map . map
next :: Int -> [[Int]]
next 0 = [[1],[0,2],[1]]
next n = sn ++ map (\a -> a ++ map (+2*3^n) a) nn ++ sn
where
nn = next (n - 1)
sn = mmap (+3^n) nn
Now, next n describes the positions of all stars. To print them, we first compute the relative distances.
diffs :: [Int] -> [Int]
diffs (x:xs) = x: diffs' x (xs)
where
diffs' x (y:ys) = y - x - 1 : diffs' y ys
diffs' _ [] = []
diffs [] = []
lpad :: Int -> [[Char]]
lpad = map (concatMap $ \n -> replicate n ' ' ++ "*") . map diffs . next'
Applied to one line, diffs returns the list of the number of spaces we need to put before each star and lpad generates the picture from that. Print it as before:
pretty :: Int -> IO ()
pretty n = putStrLn $ unlines $ lpad n
I liked the task, so I wrote an alternative solution.
We could build it up, a bit like you would with a pretty printer. Look into the pretty package to take these ideas and use them properly, but let's stick to plain old [String] for this.
First let's make a blank grid
blank :: Int -> [String]
blank n = replicate (3^n) $ replicate (3^n) ' '
Then let's define a diamond.
diamond :: Int -> [String]
diamond 0 = ["*"]
diamond n = let
o = diamond (n-1)
x = blank (n-1) in
joinMatrix [[x,o,x]
,[o,x,o]
,[x,o,x]]
But how can we join this matrix of [String] together?
First get all the Strings that should be concatenated together next to each other instead of under each other using transpose, then concat them all:
joinLine :: [[String]] -> [String]
joinLine = map concat.transpose
To do that to a whole matrix we need to join the lines on each row, then concat all the lines together into one list of lines:
joinMatrix :: [[[String]]] -> [String]
joinMatrix = concat.map joinLine
helper functions for printing:
put = mapM_ putStrLn
d n = put $ diamond n
You could argue that the numerical solution is more efficient, and it is, but d 4 is the largest that fits on my screen and isn't slow. You could also argue that this solution is clearer.
*Main> d 0
*
*Main> d 1
*
* *
*
*Main> d 2
*
* *
*
* *
* * * *
* *
*
* *
*
(It works for higher n too, but they would make this post unnecessarily long on the page.)
This is derived from AndrewC's solution. The space blocks are recursively generated and I prefer to use operators to make the code clearer:
diamond
= putStr
. unlines
. fst
. (iterate f (["*"], [" "]) !!)
where
f (d, e)
= ( e + d + e
++ d + e + d
++ e + d + e
, e + e + e
++ e + e + e
++ e + e + e
)
(+) = zipWith (++)
A generalization.
If we would like to have this:
+
- -
+
- -
+ + + +
- -
+
- -
+
- -
+ + + +
- -
+ + + +
- - - - - - - -
+ + + +
- -
+ + + +
- -
+
- -
+
- -
+ + + +
- -
+
- -
+
then the solution is star 3 where
star
= putStr
. unlines
. (\(d, p, e) -> d)
. (iterate f (["-"], ["+"], [" "]) !!)
where
f (d, p, e)
= ( e + p + e
++ d + e + d
++ e + p + e
, e + d + e
++ p + e + p
++ e + d + e
, e + e + e
++ e + e + e
++ e + e + e
)
(+) = zipWith (++)