简体   繁体   中英

Haskell - Recursive function, eating a string list


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
  1. How can I fix/improve this function without using libraries ?
  2. Where I can find a good intro about function definitions (especially recursion) with examples done over string lists instead of dummy numbers ?

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM