Reputation: 13
I'm new to haskell and trying to learn something while building a personal project.
I've defined a function:
pacHead :: String -> String
pacHead textrow =
let first = head textrow
in if first /= '"'
then pacHead (tail textrow)
else textrow
I want it to take a string, verify if it's head is a certain char (") and 'eat' the string up to the point the char is removed. Example:
IN: bla bla bla bla "citation" bla bla -> OUT: citation" bla bla
But, when I apply it to a list of strings (using map) it just returns an empty list.
let firstPac = map pacHead linesList
Upvotes: 0
Views: 2396
Reputation: 42796
How can I fix/improve this function without using libraries ?
First notice that your function is:
pacHead :: String -> String
pacHead = tail . dropWhile (/= '"')
Prelude> let pacHead = tail.dropWhile (/= '"')
Prelude> pacHead "bla bla bla bla \"citation\" bla bla"
"citation\" bla bla"
Recursive version (with patternt matching):
pacHead :: String -> String
pacHead "" = ""
pacHead (x:xs) | x == '"' = xs
| otherwise = pacHead xs
You first check if the string is empty, where you return an empty string, otherwise yo pattern match the string, x
becomes the first char and xs
the remaining string, if x is equal to "
you return the remaining string otherwise you continue computing the string.
Where I can find a good about functions definitions (especially recursion) with examples done over string lists instead of dummy numbers ?
Almost any example about list can be applied to string, becouse string is just a type alias
for [char]
Upvotes: 1