簡體   English   中英

如何從haskell中的列表中剪切?

[英]How can I cut from a list in haskell?

實現列表功能,將列表的一部分切掉! 第一個參數是子列表開始的索引,第二個參數是切割的長度。

list :: Int -> Int -> [b] -> [b]
list a b (x: xs) = x: sublist (a: a + b) xs

我嘗試了這個遞歸解決方案,但它不起作用。 我不知道如何制作此代碼。 我能得到一些幫助嗎?

利用前奏。 先下降,然后采取:

cut :: Int -> Int -> [a] -> [a]
cut m n = take n . drop m

例如:

> cut 2 3 [0, 1, 1, 2, 3, 5, 8, 13]
[1,2,3]

或者,如果您設置滾動自己的遞歸實現:

cut' :: Int -> Int -> [a] -> [a]
cut' 0 0 xs       = []                    -- done
cut' _ _ []       = []                    -- done
cut' 0 n (x : xs) = x : cut' 0 (n - 1) xs -- take
cut' m n (x : xs) = cut' (m - 1) n xs     -- drop

的確:

> cut' 2 3 [0, 1, 1, 2, 3, 5, 8, 13]
[1,2,3]

暫無
暫無

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

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