2016-02-03 41 views
-1

我有这个功能,我需要为我的任务构建。Haskell - 如何访问列表中的列表

该函数返回所有输入句子中所有符号的列表(无重复)。当句子和符号有以下几种类型:

-- Symbols are strings (a negative sign as the first character represents a negated symbol) 
type Symbol = String 

-- Sentence = Statements. This is a list of a list of symbols 
type Sentence = [[Symbol]] 

我试图与列表理解和递归,但我不知道如何列表中的访问列表。此外,你不需要有任何重复,为了这个,我用小块功能:

getSymbols :: [Sentence] -> [Symbol] 
getSymbols stmts = nub [ x | [x: xs] <- stmts ] 
Input: getSymbols [["A"], ["B","C"], ["C"]] 
Return: ["A", "B", "C"] 

真的很感谢一些帮助!

+1

使用降价(例如StackOverflow上的代码)时,将所有代码行缩进四个空格。另请参阅https://stackoverflow.com/editing-help#code – Zeta

回答

1

递归你可以这样定义

conc [] = [] 
conc (x:xs) = x ++ (conc xs) -- ++ concatenates two lists 

您的拼接你getSymbols成为

getSymbols sentence = nub . conc $ sentence 

关于:

getSymbols :: [Sentence] -> [Symbol] 

您确定要取那里的句子列表吗?看起来你只想用一句话来工作,特别是在看你的示例输入&输出时。如果你想使用一个句子列表,那么你可以两次将所有的符号带到同一级别。

getSymbols' :: [Sentence] -> [Symbol] 
getSymbols' sentences = nub . conc . conc $ sentences 
2

尝试适应像

[ 1000 + x | xs <- [[1,2],[3,4]] , x <- xs ]