简体   繁体   English

Haskell-递归函数,使用字符串列表

[英]Haskell - Recursive function, eating a string list


I'm new to haskell and trying to learn something while building a personal project. 我是Haskell的新手,尝试在构建个人项目时学习一些东西。

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 IN:bla 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. 但是,当我将其应用于字符串列表(使用map)时,它只会返回一个空列表。

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): 递归版本(与patternt匹配):

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. 首先检查字符串是否为空,然后返回空字符串,否则yo模式匹配该字符串, x成为第一个字符, xs成为剩余的字符串,如果x等于" ,则返回剩余的字符串,否则继续计算串。

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] 关于列表的几乎所有示例都可以应用于字符串,因为字符串只是[char]type alias

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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