简体   繁体   English

Haskell - 来自数组的自定义数据结构

[英]Haskell-Custom data structure from an array

I need some advice on how to list only words from Text branches in this code I have programmed.我需要一些关于如何在我编写的代码中仅列出Text分支中的单词的建议。

data Article = Text String
             | Section String [Article] deriving (Show)

myArticle :: Article
myArticle = Section "Document" [
                 Section "Introduction" [
                       Text "My intoduction",
                       Section "Notation" [Text "alpha beta gamma"]],
                 Section "Methods" [
                       Section "Functional Programming" [Text "FPR"],
                       Section "Logical Programming" [Text "LPR"]],
                 Section "Results" [Text "All is great"]]

tex :: Article -> [String]
tex (Text x) = [x]
tex (Section x (l:ls)) = tex l

I tried to call ls in the tex function, but it throws me an error.我试图在tex function 中调用 ls,但它抛出了一个错误。 I don't know how to proceed.我不知道如何进行。

You're looking for the concatMap function .您正在寻找concatMap function This will run the function you give it on each element of the input list, and concatenate all of the results together into a single list.这将在输入列表的每个元素上运行您给它的 function,并将所有结果连接到一个列表中。 Also, you don't need to use : to bind a list unless you actually want to break it into its head and tail (and in your case, you don't).此外,您不需要使用:来绑定列表,除非您真的想将它分成头部和尾部(在您的情况下,您不需要)。 So change the last line of your code to this:因此,将代码的最后一行更改为:

tex (Section x ls) = concatMap tex ls

And then tex myArticle will be ["My intoduction","alpha beta gamma","FPR","LPR","All is great"] .然后tex myArticle将是["My intoduction","alpha beta gamma","FPR","LPR","All is great"]

You pattern match with (l:ls) , which means it is a non-empty list, and you only work with l , so the first item, you "ignore" the rest of the Article s (which can be Text s and Section s).您使用(l:ls)进行模式匹配,这意味着它是一个非空列表,并且您只使用l ,因此第一项,您“忽略” Article的 rest(可以是TextSection秒)。

You can match with any list, and then have to process that list by generating a list of String s for each subitem, and concatenating these, so:您可以匹配任何列表,然后必须通过为每个子项生成String列表并将它们连接起来来处理该列表,因此:

tex :: Article -> [String]
tex (Text x) = [x]
tex (Section _ ls) = … ls

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

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