我需要打印奇数索引的元素。目前正在打印索引。
我不明白如何打印这个索引的元素?
f :: [Int] -> [Int]
f lst = filter odd [0..length lst]
-- I can't edit this part
main = do
inputdata <- getContents
mapM_ (putStrLn. show). f. map read. lines $ inputdata
我需要打印奇数索引的元素。目前正在打印索引。
我不明白如何打印这个索引的元素?
f :: [Int] -> [Int]
f lst = filter odd [0..length lst]
-- I can't edit this part
main = do
inputdata <- getContents
mapM_ (putStrLn. show). f. map read. lines $ inputdata
如果您想“步行”完成此操作:
odds [] = []
odds [x] = []
odds (e1:e2:xs) = e2 : odds xs
你可以使用zip
函数将你的[Int]
转换为一个[(Int, Int)]
,其中第一个元素是索引,第二个元素是原始值。然后你可以使用fst
和snd
来获取你想要的结果:
f :: [a] -> [a]
f lst = map fst $ filter (odd.snd) indexed where
indexed = zip lst [0..]
请注意,没有必要将此限制为 Int
列表,它现在可以在任何类型的列表上运行:
> f "qwertyuiopasdfghjklzxcvbnm"
"wryipsfhkzcbm"
Prelude> map snd $ filter (odd . fst) (zip [0 .. ] ["aa", "bb", "cc", "dd"])
["bb","dd"]
f = map snd . filter (odd . fst) . zip [0..]
- dopamanePrelude> let arr = [0..10]
Prelude> [j | (i, j) <- zip [0..] arr, odd i]
[1,3,5,7,9]
f :: [Int] -> [Int]
f lst = [lst!!i|i<-[1..length lst],odd i]
我发现还有另外两种实现f函数的方法非常优雅:
f lst = map (lst!!) [1, 3..(length lst)]
并且
import Data.List.Split
f lst = concatMap (drop 1) (chunksOf 2 lst)
lst[0..]
。非常感谢,Vic! - rel1x