簡體   English   中英

從列表中獲取X個第一個元素

[英]Get X first elements out of list

讓我們考慮兩個列表: ["a","b","c"]["a","b","c","d","e","f"]

我想檢查第一個列表是否是我認為可以使用的另一個列表的開頭:

["a","b","c"] == head (splitAt (length ["a","b","c"]) ["a","b","c","d","e","f"])

不幸的是,這不起作用。 還有另一種方法可以從新列表中的列表中獲取第一個3個第一個元素嗎?

您可以使用zipWith避免遍歷列表兩次,而不是使用take 當您調用length ,首先必須遍歷較短的列表,然后從較長的列表中獲取那么多值,然后遍歷列表,逐個元素地進行比較。 更有意義的是同時遍歷兩個列表,在較短的列表到期時停止比較。 zipWith提供了這個功能:

-- Definitions for `and` and `zipWith` in `Prelude`
--
-- and :: [Bool] -> Bool
-- and [] = True
-- and (x:xs) = x && and xs
--
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
-- zipWith f (x:xs) (y:ys) = f x y : zipWith f xs ys
-- zipWith _ _      _      = []

sameStartingElements :: Eq a => [a] -> [a] -> Bool
sameStartingElements xs ys = and $ zipWith (==) xs ys

由於懶惰,這個定義只會遍歷兩個列表,並且只要其中一個列出元素就會停止。 這將更有效,並且它避免了必須知道任一列表的長度。

我想檢查第一個列表是否是另一個列表的開頭。

您可以使用isPrefixOf從Data.List模塊中。

你要找的功能是take 看到這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM