How to find occurrences of char in an input string in Haskell - haskell

I am trying to write a function that will take a String and a Char and output the indexes where the char occurs in the string.
stringCount str ch =
Input : "haskell is hard" `h`
Output:[0,11]
Input : "haskell is hard" `a`
Output:[1,12]
Please help me I'm struggling to understand Haskell.

There are many ways to do this, but since you mention you're a Haskell beginner, a list comprehension may be easiest to understand (I'm assuming this is homework, so you have to implement it yourself, not use elemIndices):
stringCount str ch = [ y | (x, y) <- zip str [0..], x == ch ]
stringCount "haskell is hard" 'a'
-- [1,12]
stringCount "haskell is hard" 'h'
-- [0,11]
Here we zip, the string str with the infinite list starting from 0, producing the tuples ('h', 0), ('a', 1), ('s', 2), etc. We then only select the tuples where the character (bound to x) equals the argument ch and return the index (bound to y) for each of them.
If you wanted to keep your current argument order but use elementIndices you can use the following:
stringCount' = flip elemIndices
stringCount' "haskell is hard" 'h'
-- [0,11]

Here is a simpler but less sophisticated solution that the one post by karakfa:
stringCount :: String -> Char -> Integer -> [Integer]
stringCount [] c _ = []
stringCount (x:xs) c pos | x == c = pos:(stringCount xs c (pos+1))
| otherwise = stringCount xs c (pos+1)
The idea is that you go through the string char by char using recursion and then compare the actual caracter (head at the moment) with the char passed as argument. To keep track of the position I am using a counter called pos, and increment it for each recursion call.

you can use elemIndex to walk through the list, or simply write your own
indexOf x = map fst . filter (\(_,s) -> s==x) . zip [0..]
indexOf 'a' "haskell is hard"
[1,12]
or with findIndices
import Data.List(findIndices)
findIndices (\x -> x=='a') "haskell is hard"
[1,12]

Related

Do notation in haskell

So I am trying to program a function in haskell which does the following things:
1. Input is a string
2. function first removes all letters of the string and only numbers remain
3. function converts the string numbers to int numbers
4. function sums the numbers in the string together and prints it out
My Code til' Step #3
func str =
do
str <- filter (< 'a') str
str2 <- map digitToInt str
return str2
somehow this doesn't work if I remove the 4th line with map digitToInt it works til step #2 fine but I dont know what the problem here is
The Error is an couldnt match expected type [Char] with actual type Char
Thank you in advance
You don't want do notation at all, just normal variable binding. So:
func str = str2 where
str1 = filter (<'a') str
str2 = map digitToInt str1
Tracking the most recently used name is annoying, isn't it? Plus it's easy to make a mistake and type str instead of str1 somewhere, or similar. Enter function composition:
func str = str2 where
str2 = (map digitToInt . filter (<'a')) str
In fact, I would inline the definition of str2, then elide str entirely:
func = map digitToInt . filter (<'a')
I would prefer to use isDigit over (<'a'); we can toss in a sum at the same time.
func = sum . map digitToInt . filter isDigit
Reads nice and clean, in my opinion.
You could use do notation, since strings are lists and lists are monads. It would look like this, though:
func :: String -> [Int]
func str = do
c <- filter (< 'a') str -- Get one character
return (digitToInt c) -- Change that character to a integer
What is the value of c? It's not just one character, but all of them. The list monad models nondeterminism. Imagine that func makes multiple copies of itself, with each copy selecting a different character c from the input string. return makes a new list from the result, and the monad takes care of glue the individual lists into a one final list. It's a little clearer if you compare it its deconstructed form.
func str = filter (< 'a') str >>= \c -> return (digitToInt c)
Since xs >>= f = concatMap f xs and return x = [x] in the Monad [] instance, it becomes:
func str = concatMap (\c -> [digitToInt c]) (filter (< 'a') str)
However, the monadic form isn't necessary, as your function only needs to make use of the Functor instance of [], since every element from the first list corresponds to exactly one element in the final list:
-- Or in a form closer to Daniel Wagner's answer
func str = fmap digitToInt (filter (< 'a') str)

How to destructure a string into first, middle, and last?

I'm writing a function to determine whether a number is a palindrome.
What I would like to do in the first case is to destructure the string into the first character, all the characters in the middle, and the last character. What I do is check if the first character is equal to the last, and then if so, proceed to check the middle characters.
What I have is below, but it generates type errors upon compilation.
numberIsPalindrome :: Int -> Bool
numberIsPalindrome n =
case nString of
(x:xs:y) -> (x == y) && numberIsPalindrome xs
(x:y) -> x == y
x -> True
where nString = show n
Using the String representation is cheating...
Not really, but this is more fun:
import Data.List
palindrome n = list == reverse list where
list = unfoldr f n
f 0 = Nothing
f k = Just (k `mod` 10, k `div` 10)
What it does is creating a list of digits of the number (unfoldr is really useful for such tasks), and then comparing whether the list stays the same when reversed.
What you try has several problems, e.g. you miss a conversion from the number to a String (which is just a list of Char in Haskell), and lists work completely different from what you try: Think of them more as stacks, where you usually operate only on one end.
That said, there is an init and a last function for lists, which allow to work your way from the "outer" elements of the list to the inner ones. A naive (and inefficient) implementation could look like this:
palindrome n = f (show n) where
f [] = True
f [_] = True
f (x : xs) = (x == last xs) && (f (init xs))
But this is only for demonstration purposes, don't use such code in real live...
The definition you probably want is
numberIsPalindrome :: Int -> Bool
numberIsPalindrome num = let str = show num
in (str == reverse str)
The (:) operator is known as cons, it prepends items to lists:
1:2:[] results in [1,2]
You are getting a type error because you are trying to compare the first argument, a Char, with the last one, a [a].
If you really would like to compare the first with the last you would use head and last.
But you are better using the solution that taktoa proposed:
numberIsPalindrome :: Int -> Bool
numberIsPalindrome num =
numberString == reverse numberString
where numberString = show num

Count a occurrence of a specific word in a sentence haskell

I'm new in Haskell and I'm tring to write a simple function that counts the number of occurences of a substring in a string.
For example : "There is an apple" and I want to count how many times "is" in the sentence, in this case the result should be 1.
This is what I've tried:
countOf :: String -> Int
countOf x = length [n | n <- words x, filter "is" x]
According what I've studied it should work, but it doesn't. I really don't know how to solve the problem, and also don't know what the error message I get means:
input:1:41:
Couldn't match expected type `Bool' with actual type `[a0]'
In the return type of a call of `filter'
In the expression: filter "a" x
In a stmt of a list comprehension: filter "a" x
The function filter has the type
filter :: (a -> Bool) -> [a] -> [a]
This means that its first argument is another function, which takes an element and returns a Bool, and it applies this function to each element of the second argument. You're giving a String as the first argument instead of a function. Maybe you want something more like
countOf x = length [n | n <- words x, filter (\w -> w == "is") x]
But this won't work either! This is because any extra expression in a list comprehension has to be a Bool, not a list. filter returns a list of elements, not a Bool, and this is actually the source of your compiler error, it expects a Bool but it sees a list of type [a0] (it hasn't even gotten far enough to realize it should be [String]).
Instead, you could do
countOf x = length [n | n <- words x, n == "is"]
And this would be equivalent to
countOf x = length (filter (\w -> w == "is") (words x))
Or with $:
countOf x = length $ filter (\w -> w == "is") $ words x
Haskell will actually let us simplify this even further to
countOf x = length $ filter (== "is") $ words x
Which uses what is known as an operator section. You can then make it completely point free as
countOf = length . filter (== "is") . words
I would do like this:
countOf :: String -> Int
countOf x = length [n | n <- words x, compare "is" n == EQ]
Demo in ghci:
ghci> countOf "There is an apple"
1
You can put the comparison straight in the comprehension:
countOf x = length [n | n <- words x, n == "is"]
Actually, you try to count the number of occurences of a word in a string. In case you look for a substring:
import Data.List (inits, tails)
countOf = length . filter (=="is") . conSubsequences
where
conSubsequences = concatMap inits . tails
One could also try a foldr:
countOf :: String -> Int
countOf x = foldr count 0 (words x)
where
count x acc = if x == "is" then acc + 1 else acc

I need convert this string in Char List

I'm learning haskell. I'm reading a string from a text file and need to make this string becomes a list of char.
The input file is this:
Individuo A; TACGATCAAAGCT
Individuo B; AATCGCAT
Individuo C; TAAATCCGATCAAAGAGAGGACTTA
I need convert this string
S1 = "AAACCGGTTAAACCCGGGG" in S1 =
["A","A","A","C","C","G","G","T","T","A","A","A","C","C","C","G","G","G","G"]
or S1 =
['A','A','A','C','C','G','G','T','T','A','A','A','C','C','C','G','G','G','G']
but they are separated by ";"
What should I do?
What can I do?
after getting two lists, I send them to this code:
lcsList :: Eq a => [a] -> [a] -> [a]
lcsList [] _ = []
lcsList _ [] = []
lcsList (x:xs) (y:ys) = if x == y
then x : lcsList xs ys
else
let lcs1 = lcsList (x:xs) ys
lcs2 = lcsList xs (y:ys)
in if (length lcs1) > (length lcs2)
then lcs1
else lcs2
A rough and ready way to split out each of those strings is with something like this - which you can try in ghci
let a = "Individuo A; TACGATCAAAGCT"
tail $ dropWhile (/= ' ') $ dropWhile (/= ';') a
which gives you:
"TACGATCAAAGCT"
And since a String is just a list of Char, this is the same as:
['T', 'A', 'C', 'G', ...
If your file consists of several lines, it is quite simple: you just need to skip everything until you find “;”. If your file consists of just one line, you’ll have to look for sequences’ beginnings and endings separately (hint: sequence ends with space). Write a recursive function to do the task, and use functions takeWhile, dropWhile.
A String is already a list of Char (it is even defined like this: type String = [Char]), so you don’t have to do anything else. If you need a list of Strings, where every String consists of just one char, then use map to wrap every char (once again, every String is a list, so you are allowed to use map on these). To wrap a char, there are three alternatives:
Use lambda function: map (\c -> [c]) s
Use operator section: map (:[]) s
Define a new function: wrap x = [x]
Good luck!

Haskell function that returns number of elements that overlap

How would you go about defining a function that takes two strings, say string x and string y and return the number of elements at the end of the first string (string x) which overlap with the beginning of the second string (second y).
I'm thinking that it would be a good idea to use isPrefixOf from the prelude to do this since it checks if a string is in another string and returns True if it does or False otherwise. But I'm a little confused at how to return the count of how many elements overlap. I wrote some pseudocode based off how I think you would approach the problem.
countElements :: Eq a => (Str a, Str a) -> Int
countElements (x,y) =
if x `isPrefixOf` y == True
then return the count of how many elements overlap
otherwise 0
A sample output would be:
countElements (board, directors) = 1
countElements (bend, ending) = 3
Any help here? I'm not very good at writing Haskell code.
You have exactly the right idea, but your pseudocode misses the fact that you'll have to iterate on all of the possible tails of the first string passed to the function.
countElements :: String -> String -> Int
countElements s t = length $ head $ filter (`isPrefixOf` t) (tails s)
> countElements "board" "directors"
1
> countElements "bend" "endings"
3
Version without isPrefixOf:
import Data.List
countElements xs ys = length . fst . last . filter (uncurry (==)) $ zip (reverse $ tails xs) (inits ys)

Resources