简体   繁体   English

Haskell:返回值,状态和状态单子

[英]Haskell: return value, state, and state monads

I'm making a function that does 我正在做一个功能

(a->Bool) -> [a] -> State [a] [a]

and I was wondering if there was a simple way to go through the list storing "failed" items that didn't pass the predicate as the state and the "passing" items as the value that will eventually be returned? 我想知道是否有一种简单的方法来遍历列表,该列表存储未通过谓词作为状态的“失败”项目和将最终返回的“通过”项目作为值? You would see both the return value and the state. 您将看到返回值和状态。 Samples: 样品:

*CL> runState (func (<3) [1, 2, 3]) []
([1, 2], [3])
*CL> runState (func even [1, 2, 3]) [10]
([2], [10, 1, 3])

I've looked long and hard for answers and haven't found anything on this specific situation yet. 我一直在努力寻找答案,但在这种特定情况下还没有找到任何东西。 I know I can do it differently as I have, but I specifically want to know if I can do it in the way mentioned above. 我知道我可以像以前一样做不同的事情,但是我特别想知道是否可以按照上述方式做。

You don't really need to use state for this since you could return a pair of (passed, failed) but you can do: 您实际上不需要为此使用状态,因为您可以返回一对(passed, failed)但是您可以执行以下操作:

partitionSt :: (a->Bool) -> [a] -> State [a] [a]
partitionSt f l = do
  let (passed, failed) = partition f l
  s <- return passed
  put failed
  return s

or 要么

partitionSt f l = return passed <* (put failed)
  where (passed, failed) = partition f l

Alright I figured it out. 好吧,我知道了。 I'm supposed to bind both the return value and the next iteration of the state and return that, otherwise just updating the state and iterating through. 我应该绑定返回值和状态的下一次迭代并返回它,否则只需更新状态并进行迭代即可。 Lee did put me on the right track by showing me I could bind the return value. Lee通过向我展示我可以绑定返回值,确实使我走上了正确的轨道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM