我想要一个接收列表并索引所有内容的函数:indexed :: [a] -> [(Int, a)].或者返回的值可以是Monad,只要它包含原始列表的索引值即可.
我认为在处理每个元素时我需要StateT来临时记住和索引索引号,但我不熟悉Monad变换器的东西,我需要一些帮助来编写函数.
我相信它看起来与此相似(这肯定不起作用):
indexed ns = do
n <- ns
i <- get
put (i + 1)
return (i, n)
Run Code Online (Sandbox Code Playgroud)
你会怎么写的?
没有必要去解决所有麻烦.
indexed = zip [0..]
Run Code Online (Sandbox Code Playgroud)
如果你想使用monad变换器,我认为是这样的:
indexed :: [a] -> [(Int, a)]
indexed ns = evalState (runListT lt) 0 where
lt = do
n <- ListT $ return ns
i <- get <* modify (+1)
return (i, n)
Run Code Online (Sandbox Code Playgroud)