![](/img/trans.png)
[英]Haskell: A function that takes a list xs and an integer n and returns all list of length n with elements from xs
[英]Trying to create a function that takes a list and returns a list of all of all elements identical to its first element, but my function isn't working
特別是一個字符串。 所以它需要["so", "what", "and", "so", "for" "so"]
並返回["so", "so", "so"]
。 我的問題是我的函數返回一個與輸入的列表相同的列表。
這是所有相關的代碼:
lookAhead :: [String] -> String
lookAhead [] = []
lookAhead (c:cs) = c
groupFirst :: [String] -> [String]
groupFirst [] = []
groupFirst (x:xs)
| lookAhead xs == x = x : (groupFirst ((lookAhead xs):(tail xs)))
| lookAhead xs /= x = x : (groupFirst xs)
| lookAhead xs == [] = x : []
trail
作為head-element-equality-predicated filter
:
trail :: Eq a => [a] -> [a]
trail [] = []
trail (x : xs) = x : filter (== x) xs
trailBy
使用Schwartzian變換和memoization :
trailBy :: Eq b => (a -> b) -> [a] -> [a]
trailBy _ [] = []
trailBy f (x1 : xs) = let x1f = f x1
in x1 : filter (\ x -> f x == x1f) xs
trail = trailBy id
,其中id x = x
,Haskell的標識函數。
你的實現的問題是在groupFirst
,你在列表上進行迭代並將列表尾部(其類型為[String]
)與列表的頭部( String
)進行比較。 因此,每個比較都將由第二個守衛匹配,在那里你最終建立一個相同的列表。
您需要找到一種方法來使第一個字符串可供比較,這樣您就可以在不更改函數調用的情況下迭代列表(我們需要一些形式為f strList
,而不是f firstStr strList
)。 通過讓函數調用另一個函數來解決這個問題的一種方法,將列表的頭部作為參數傳遞:
lookAhead :: [String] -> [String]
lookAhead [] = []
lookAhead (x:xs) = x : check x xs
check :: String -> [String] -> [String]
check str = foldr (\x acc -> if x == str then x:acc else acc) []
lookAhead
函數返回第一個元素,並且該值正在groupFirst
函數中遞歸更新。 你可以做到的一種方法是使用列表理解:
groupFirst :: [String] -> [String]
groupFirst [] = []
groupFirst list = [x | x <- list, head list == x]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.