2016-02-03 38 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 ]