gpt4 book ai didi

loops - 从列表中删除的项目回来

转载 作者:行者123 更新时间:2023-12-05 08:29:22 27 4
gpt4 key购买 nike

我想从列表中删除一个项目,但它又回来了。

main = do
let y = ["aa","bb","cc","dd","ee","ff"]
let n = length y
replicateM_ (n-1) (deleteWord y)

deleteWord y = do
putStrLn "Write a word: "
word <- getLine
let new_y = delete word y
print new_y

输出:

*Main> main
Write a word:
aa
["bb","cc","dd","ee","ff"]
Write a word:
bb
["aa","cc","dd","ee","ff"]
Write a word:
cc
["aa","bb","dd","ee","ff"]

我希望 "aa""bb" 保持删除状态,不再返回到列表中。

最佳答案

正如评论中所解释的那样,y 值一旦定义,就像 Haskell 中的每个值一样是不可变的。

但是有一个monadic库函数,nest :: Monad m => Int -> (a -> m a) -> a -> m a ,这允许您将某个操作的结果重新注入(inject)到同一个操作中,多次。

为了使用它,您的基本操作需要返回一个结果:

$ ghci
GHCi, version 8.8.4: https://www.haskell.org/ghc/ :? for help
...
λ>
λ> import Data.List(delete)
λ> import Control.Monad.HT(nest)
λ>
λ>
λ> :{
|λ> deleteWord y = do
|λ> putStrLn "Write a word: "
|λ> word <- getLine
|λ> let new_y = delete word y
|λ> print new_y
|λ> return new_y -- HERE !!!
|λ> :}
λ>
λ> :type deleteWord
deleteWord :: [String] -> IO [String]
λ>
λ> action3 = nest 3 deleteWord
λ>
λ> :type action3
action3 :: [String] -> IO [String]
λ>

那么让我们尝试运行那个嵌套操作:

 λ> 
λ> res3 <- action3 ["aa","bb","cc","dd","ee","ff"]
Write a word:
ff
["aa","bb","cc","dd","ee"]
Write a word:
aa
["bb","cc","dd","ee"]
Write a word:
dd
["bb","cc","ee"]
λ>
λ>
λ> res3
["bb","cc","ee"]
λ>

附录:

source code for nest对于初学者 Haskell 程序员来说,这可能不是很有启发性。但库源代码的主要目标是最大限度地提高运行时效率。

可以写一个更简单的递归明确的版本:

myNest :: Monad m => Int -> (a -> m a) -> a -> m a
myNest n fn a0 =
if (n <= 0) then (return a0)
else do
a1 <- fn a0
myNest (n-1) fn a1

关于loops - 从列表中删除的项目回来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71110804/

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