gpt4 book ai didi

haskell - 状态 Monad : Modifying state without modifying value

转载 作者:行者123 更新时间:2023-12-03 22:15:58 28 4
gpt4 key购买 nike

我正在编写一个函数,它接受一个谓词 p 和一个列表。它返回 ([value],[state]),其中第一个列表包含通过 p 的元素,第二个列表包含未通过的元素。但是,当我运行

runState (myFunc even [1,2,3,4,5]) [] 

我得到 ([2,4,5,3,1],[5,3,1]),其中失败的元素被错误地存储在 [value]。我相信这是由于 get 更新了状态和值,但我一直无法找到一种方法来更新状态并单独保留值,所以我想知道我将如何做到这一点.

myFunc :: (a->Bool) -> [a] -> State [a] [a]
myFunc _ [] = do
a <- get
return a
myFunc p (x:xs) = do
if (p x) then do
s <- myFunc p xs
let ret = (x:s)
return ret
else do
s <- get
put(x:s)
myFunc p xs

最佳答案

您的 myFunc _ [] 定义确实是将状态放入值中。你实际上只是希望它是一个空的通行证列表:

myFunc _ [] = return []

然后您可能希望按顺序返回结果:

myFunc :: (a -> Bool) -> [a] -> State [a] [a]
myFunc _ [] = return []
myFunc p (x:xs) = do
passes <- myFunc p xs

if p x then
return (x:passes)
else do
modify (x:)
return passes

虽然它可能是状态练习,但写它的方式很酷partition已经存在,

import Data.Bifunctor

partition f = foldr m ([], [])
where m x = (if f x then first else second) (x:)

关于haskell - 状态 Monad : Modifying state without modifying value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43219093/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com