Haskell - string function - string

I need to write function, which is seeking for "Z" in string, and when this function finds it on i index, it appends i+3 Char to table.
Here is my code:
someFun :: String => String -> String -> String
someFun "" (r:rs) = (r:rs)
someFun (a:b:c:d:xs) (r:rs)
| a == "Z" = someFun xs ((r:rs)++d)
| otherwise = someFun (b:c:d:xs) (r:rs)
I got bunch of errors that I don't know how to fix due to my poor experience in Haskell programming.
EDIT:
If input is "(C (N (Z 'p')) (A (K (Z 'p') (Z 'q')) (Z 'r')))"
its output should be: ['p','q','r']

The specification is not entirely clear, but it sounds like you want to collect all the characters which occur three places after a 'Z' in the input, so that from
"BUZZARD BAZOOKA ZOOM"
we get
"RDKM"
Without a clearer presentation of the problem, it is difficult to give precise advice. But I hope I can help you get past some of the small irritations, so that you can engage with the actual logic of the problem.
Let's start with the type. You have
someFun :: String => String -> String -> String
but left of => is the place for properties of type expressions, usually involving variables that could stand for lots of types, such as Eq a (meaning that whatever type a is, we can test equality). String is a type, not a property, so it cannot stand left of =>. Drop it. That gives
someFun :: String -- input
-> String -- accumulating the output (?)
-> String -- output
It is not clear whether you really need an accumulator. Suppose you know the output for
"ZARD BAZOOKA BOOM" -- "DKM", right?
Can you compute the output for
"ZZARD BAZOOKA BOOM" -- "RDKM"
? Just an extra 'R' on the front, right? You're using tail recursion to do the next thing, when it is usually simpler to think about what things should be. If you know what the output is for the tail of the list, then say what the output is for the whole of the list. Why not just map input to output directly, so
someFun :: String -> String
Now, pattern matching, start with the simplest possible pattern
someFun s = undefined
Can you see enough about the input to determine the output? Clearly not. It matters whether the input is empty or has a first character. Split into two cases.
someFun "" = undefined
someFun (c : s) = undefined -- c is the first Char, s is the rest of the String
It also matters whether the first character is 'Z' or not. Be careful to use single quotes for Char and double quotes for String: they are different types.
someFun "" = undefined
someFun ('Z' : s) = undefined -- the first Char is Z
someFun (c : s) = undefined
In the case wit 'Z', you also want to make sure that s has at least three characters, and we care about the third, so
someFun "" = undefined -- input empty
someFun ('Z' : s#(_ : _ : d : _)) = undefined -- first is 'Z' and d is 3 later
someFun (c : s) = undefined -- input nonempty
The # is an "as pattern", allowing me to name the whole tail s and also check that it matches (_ : _ : d : _), grabbing the third character after the 'Z'.
So far, I've given no thought to the output, just what I need to see about the input. Let's figure out what the output must be. In the first case, empty input gives empty output
someFun "" = ""
someFun ('Z' : s#(_ : _ : d : _)) = undefined -- first is 'Z' and d is 3 later
someFun (c : s) = undefined -- input nonempty
and in the other two cases, we can assume that someFun s already tells us the output for the tail of the list, so we just need to figure out how to finish the output for the whole list. In the last line, the output for the tail is just what we want.
someFun "" = ""
someFun ('Z' : s#(_ : _ : d : _)) = undefined -- first is 'Z' and d is 3 later
someFun (c : s) = someFun s
But in the case where we've found that d is three places after the initial 'Z', we need to make sure d is at the start of the output.
someFun "" = ""
someFun ('Z' : s#(_ : _ : d : _)) = d : someFun s
someFun (c : s) = someFun s
Just checking:
*Main> someFun "BUZZARD BAZOOKA ZOOM"
"RDKM"
The key idea is to figure out how to express the output for the whole input in terms of the output for its pieces: what it is, not what to do. Here, you can assume that the output for the tail, s is correctly computed, so you just need to figure out whether you have anything extra to return.

It's not really clear what you're trying to do but this compiles:
someFun :: String -> String -> String
someFun "" (r:rs) = (r:rs)
someFun (a:b:c:d:xs) (r:rs)
| a == 'Z' = someFun xs ((r:rs)++[d])
| otherwise = someFun (b:c:d:xs) (r:rs)
The String => is for typeclass constraints, which you don't need.
d is a Char while (++) is defined on lists (of Chars in this case).
Your function has incomplete pattern matches, so you could also define those, which will simplify the existing cases:
someFun :: String -> String -> String
someFun _ [] = error "Empty string"
someFun "" s = s
someFun ('Z':b:c:d:xs) s = someFun xs (s++[d])
someFun (_:b:c:d:xs) s = someFun (b:c:d:xs) s
someFun _ _ = error "String was not in the expected format"
To display it on the screen you can use putStrLn or print:
displaySomeFun :: String -> String -> IO ()
displaySomeFun s1 s2 = putStrLn (someFun s1 s2)

Lee showed how you get it to compile.
There are still some things to say about:
You have to provide more pattern-cases, You get an error for example if you try to run someFun "" "", or someFun "A" "ABCD"
First improvement: Change (r:rs) to rs, you never use r, so you can change it to a more general case (that will fix the error on someFun "" "").
The other thing is, that you don't pattern match on lists with one, two, or tree elements.
You could add someFun _ rs = rs, so that in those cases nothing happens.

Read about head and tail.It is easier with them.And end the cycle when the length of your first list is less than 4.
someFun [] rs = rs
someFun xs rs
| (length xs) < 4 = rs
| (head xs) == 'Z' = someFun (tail xs) (rs ++ [head (tail (tail (tail xs)))])
| otherwise = someFun (tail xs) rs

You can take advantage of how failing pattern-matches work in list comprehensions and the Data.List.tails function:
import Data.List (tails)
someFun :: String -> String
someFun s = [x | 'Z':_:_:x:_ <- tails s]
The tails function gives you all tails of a list (remember that a String ist just a list of Char), e.g.:
λ: tails "Overflow"
["Overflow","verflow","erflow","rflow","flow","low","ow","w",""]
The pattern ('Z':_:_:x:_) matches any string which starts with a Z and is at least four characters in size. For each pattern match, the character which is three positions after Z is extracted.
The magical part about it is that when the pattern fails (e.g. for tails which don't start with a Z or which are too short), the element is skipped silently and doesn't contribute to the result - exactly what you seem to request.

Related

How to parse a string in haskell?

i m not familiar with askell.
i have to do this function parseChar :: Char -> Parser Char
> parseChar 'a' " abcd "
Just ('a', "bcd")
> parseChar 'z' " abcd "
Nothing
i did this function
type Parser r = String -> Maybe (Char, String)
parseChar :: Char -> Parser Char
parseChar x = \xs -> Just(x, xs)
i dont really understand the \ and how can I take all the string except the second.
Thanks!!
i dont really understand the \ and how can I take all the string except the second.
The \ is a lambda expression \xs -> … is a function that maps a variable xs to the … part. Here you can however move the variable to the head of the clause.
You however need to check if the first element of the string is indeed the element you are parsing:
parseChar :: Char -> Parser Char
parseChar _ "" = Nothing
parseChar x (y:ys)
| x == y = Just (y, ys)
| otherwise = Nothing
Here x is thus the char we want to parse, and "" or (y:ys) the string that we are parsing. "" means that the string is empty, in which case we return Nothing. If the string is not empty, we unpack it in the first character (head) y, and the list of remaining characters (tail) ys. In case x == y, we are thus parsing the correct character, and we can return a 2-tuple wrapped in a Just constructor. In case x is not equal to y, the parser should "fail" and return Nothing.
This then yields:
Prelude> parseChar 'a' "abcd"
Just ('a',"bcd")
Prelude> parseChar 'z' "abcd"
Nothing
Prelude> parseChar 'a' ""
Nothing

Palindroms & Monads

I'm new to the Haskell. I am finding following task difficult:
Enter a string of characters. Output all palindromes to the file (use the IO monad to work with the file system and input / output, use the list monad to work with the strings).`
Any code is may be helpful. Thank you in advance!
This is what I have tried so far:
palindrome :: Char -> [String]
palindrome n
| n < 0 = []
| even n = map (\front -> front ++ reverse front) fronts
| odd n = map (\front -> front ++ tail (reverse front)) fronts
where ispalindrome :: (Integral a, Show a) => a -> Bool
ispalindrome x = show x = reverse (show x)
main = do
input <- getline
putStrLn print :: IO ()
So this is basically consists of 4 things.
Read Input from the stdin
Convert input string into list of strings
From the above list find out the strings which are palindromes
print these palindromes into file.
If you convert above into functions the signatures of these will be.
String -> [String]
[String] -> [String]
Don't bother about the signature of 1st and 4th for now. These are anyways one line code readily available on internet.
2 is a single function available in Data.List called words.
3 can be again in two parts. A function which find out if a given string is palindrome. Signature will be
String -> Bool
This is also one line code.
Once you have above function the only part remaining is filtering out the strings which are palindromes in given list of strings.
isPalindrome
My haskell is a bit rusty so I don't promise the code below will work %100 yet I tried to stick to the main idea.I hope this answer helps. If you think anything is wrong both logically and syntactically, just write a comment and I will fix it asap.
isPalindrome :: [Char] -> Boolean
isPalindrome w = isPalindrome' w reverse w
where
isPalindrome' :: [Char] -> [Char] -> Boolean
isPalindrome' [] [] = true
isPalindrome' (x:xs) (y:ys) = if x == y then isPalindrome' xs ys else false
isPalindrome' _ _ = false
function above should be fine for checking for palindromes.
for writing to file part, you can create a list of palindromes first, then write all palindromes to a file in another function. so basically, first you split your string into words, then for words in given string you find palindromes, then you write the palindromes into a file.
how to read string from user?
main = do
userInput <- getLine
how to split word with delimiter?
split :: Char -> [Char] -> [[Char]]
split delimiter string = split' delimiter string [] []
where
split' :: Char -> [Char] -> [Char] -> [[Char]] -> [[Char]]
split' delim [] substr splittedStr = splittedStr if substr == [] else reverse substr ++ splittedStr
split' delim (x:xs) substr splittedStr = if x == delim then split' delim xs [] (reverse substr) ++ splittedSubstr else split' delim xs (x ++ substr) splittedSubstr
main idea is you stack characters until you see your delimeter and store them in a list when you see a delimiter.
how to filter palindromes in list?
to filter palindromes in list you use haskell's filter function as
filter isPalindrome (split ' ' userInput)
In the end, you can write a main block to run all of this in right order
main = do
userInput <- getLine
let splittedInput = split ' ' userInput
let palindromes = filter isPalindrome splittedInput
let output = concat (intersperse "\n" palindromes)
writeFile "file.txt" output

Haskell - Decode message with pattern

I am new to Haskell and I am currently learning it in school. I got a school task where I have to decode a message that contain certain patterns but I have got no idea how to do this.
The pattern looks something like this: If a letter has a consonant followed by the character 'o' and then once again followed by the same consonant as before it should replace that substring ("XoX" where X is a consonant) with only the consonant. For example if I decode the string "hohejoj" it should return "hej". Sorry if I am explaining this poorly but I think you understand.
This is the code I have so far (but it doesn't work):¨
karpsravor :: String->String
karpsravor s = karpsravor_help s ""
where karpsravor_help s res
|s == "" && (last res) == 'o' = (init res)
|s==""=res
|otherwise = karpsravor_help (drop 3 s) (res ++ (consDecode (take 3 s)))
consDecode :: String->String
consDecode a
|(length a) < 3 = ""
|a == [(head a)]++"o"++[(head a)] = [(head a)]
|otherwise = a
The code is completely broken and poorly written (dumb method) but I have no other idea for how to solve this. Please help!
Pattern match to find occurrences of 'o'. I.e., use
karpsravorhelp (a:'o':b:rest) res = ...
You can't have a:'o':a:rest in the above, you can't pattern match for equality; you'll need to use a guard to make sure that a == b:
karpsravorhelp (a:'o':b:rest) res
| a == b = ...
| otherwise = ...
You'll also have to make sure a and b are consonants, which will just be an 'and' condition for the first guard. For the otherwise condition, make sure that the recursive call calls (b:rest) since you could have something like a:'o':b:'o':b:....
Also make sure to match for two other patterns:
Empty List, []
x:rest, which must go after the above pattern; this way, it will first attempt to match on the a:'o':b:rest pattern, and if that's not there, just take the next letter.
One way to do it would be with unfoldr from Data.List. You can use a case expression to pattern match on a : 'o' : b : rest, and then check that a and b are equal and not vowels using a guard |. Then just include the base cases for when the pattern doesn't match.
notVowel :: Char -> Bool
notVowel = (`notElem` "aeiouAEIOU")
karpsravor :: String -> String
karpsravor = unfoldr $ \str -> case str of
a : 'o' : b : rest
| a == b && notVowel a -> Just (a, rest)
a : rest -> Just (a, rest)
"" -> Nothing

Haskell - Pattern Matching form (x:y:zs)

I am having difficulty understanding how to use pattern matching in guards.
I have this sample function, whose purpose is to return the last character in a string.
myFun :: [Char] -> Char
myFun str#(f:s:rst)
| str == "" = error "0 length string"
| length str == 1 = head str
| rst == "" = s
| otherwise = lame (s:rst)
It is failing with "Non-exhaustive patterns in function" when passed a string with a single character.
I assume that Haskell realizes it can't use the form (f:s:rst) to match a single element list, and then fails prior to trying to evaluate the call to length.
How do I make a guard that will tell Haskell what to do when there is only a single element?
You are pattern matching at the function definition level. The way you have described it, you are only covering the case where the string is at least two characters long:
myFun str#(f:s:rst)
You need to handle other cases as well. You can have a catch-all handler like this (needs to go as the last pattern):
myFun _ = ...
Or if you want to handle, for instance, the empty string, like this (prior to the catch-all):
myFun [] = ...
As to the purpose of your function, you are probably better off just using pattern matching and not using guards.
myFun :: [Char] -> Char
myFun [] = error "empty string"
myFun [x] = x
myFun (x:xs) = myFun xs
(Note that it would be more idiomatic to return a Maybe Char instead of crashing your program)
Based on the particularly helpful answer from Chad Gilbert, and some additional tinkering,
I have found a way to have my cake and eat it to.
In case anyone has a similar stumbling block, here is a way to specify uncovered cases prior to declaring your guards:
myFun :: [Char] -> Char
myFun "" = ""
myFun str#(s:rst)
| rst == "" = s
| otherwise = myFun (s:rst)
This also works with multiple args :
strSplit :: [Char] -> [[Char]] -> [[Char]]
strSplit str [] = strSplit str [""]
strSplit "" _ = [""]
strSplit str#(s1:ns) list#(x:xs)
| s1 == '|' = strSplit ns ("":list)
| ns == "" = map reverse $ ((s1 : x) : xs)
| otherwise = strSplit ns ((s1 : x) : xs)
Or with stuff using the original pattern#(first:second:rest) idea:
lastTwo :: [Char]->[Char]
lastTwo "" = ""
lastTwo [x] = [x]
lastTwo str#(f:s:rst)
| rst =="" = [f,s]
| otherwise = lastTwo (s:rst)
This is probably super obvious to folks more familiar with Haskell, but I didn't realize that you were "allowed" to just declare the function multiple times using different syntax to cover different cases.

Having trouble with isUpper function in use

Is it OK to write the otherwise part this way? The function should lower the uppercase letters and put the space in front. It keeps giving an error.
functionl s
| s==[] = error "empty"
| otherwise = [ if isUpper c then (" " ++ toLower c) else c | c <-read s::[Char] ]
First, Note that the return type of (" "++ toLower c) is a String ([Char]) if it was done properly - but it isn't. I'll show you below.
But before that, note that in this specific list comprehension, you have else c which is a single Char.
Your return types must match.
This might be a suitable replacement: concat [ if (isUpper c) then (" "++[c]) else [c] | c <-s ]
Your list comprehension is almost right as #Arnon has shown, but you could definitely implement this function more easily using recursion:
-- A descriptive name and a type signature help
-- tell other programmers what this function does
camelCaseToWords :: String -> String
camelCaseToWords [] = []
camelCaseToWords (c:cs)
| isUpper c = ' ' : toLower c : camelCaseToWords cs
| otherwise = c : camelCaseToWords cs
Now, this pattern can be abstracted to use a fold, which is Haskell's equivalent of a basic for-loop:
camelCaseToWords cs = foldr replacer [] cs
where
replacer c xs
| isUpper c = ' ' : toLower c : xs
| otherwise = c : xs
Here each step of the iteration is performed by replacer, which takes the current character c, an accumulated value xs and returns a new value to be used in the next iteration. The fold is seeded with an initial value of [], and then performed over the entire string.

Resources