我在此代码块中的功能共识方面遇到麻烦。共识的递归定义返回[Action]而不是IO [Action]。
我是Haskell的新手,不明白为什么会这样。我的印象是,不可能从返回值中删除IO。
import System.Random (randomRIO)
import Data.Ord (comparing)
import Data.List (group, sort, maximumBy)
data Action = A | B deriving (Show, Eq, Ord)
-- Sometimes returns a random action
semiRandomAction :: Bool -> Action -> IO (Action)
semiRandomAction True a = return a
semiRandomAction False _ = do
x <- randomRIO (0, 1) :: IO Int
return $ if x == 0 then A else B
-- Creates a sublist for each a_i in ls where sublist i does not contain a_i
oneOutSublists :: [a] -> [[a]]
oneOutSublists [] = []
oneOutSublists (x:xs) = xs : map (x : ) (oneOutSublists xs)
-- Returns the most common element in a list
mostCommon :: (Ord a) => [a] -> a
mostCommon = head . maximumBy (comparing length) . group . sort
-- The function in question
consensus :: [Bool] -> [Action] -> IO [Action]
consensus [x] [action] = sequence [semiRandomAction x action]
consensus xs actions = do
let xs' = oneOutSublists xs
actions' = map (replicate $ length xs') actions
replies <- mapM (uncurry $ consensus) (zip xs' actions')
map mostCommon replies -- < The problem line
main = do
let xs = [True, False, False]
actions = [A, A, A]
result <- consensus xs actions
print result
ghc输出
➜ ~ stack ghc example.hs
[1 of 1] Compiling Main ( example.hs, example.o )
example.hs:29:3: error:
• Couldn't match type ‘[]’ with ‘IO’
Expected type: IO [Action]
Actual type: [Action]
• In a stmt of a 'do' block: map mostCommon replies
In the expression:
do let xs' = oneOutSublists xs
actions' = map (replicate $ length xs') actions
replies <- mapM (uncurry $ consensus) (zip xs' actions')
map mostCommon replies
In an equation for ‘consensus’:
consensus xs actions
= do let xs' = ...
....
replies <- mapM (uncurry $ consensus) (zip xs' actions')
map mostCommon replies
|
29 | map mostCommon replies
|
我想你要找的是
return $ map mostCommon replies
return
是将值包装到monad中的标准函数。
您可以这样想:
IO a
[] Action
(这只是另一种写作方式[Action]
)所以这里有两个错误:
[Action]
vs IO [Action]
)[]
和期望IO
)的类型不匹配在return
此处使用功能时,可以同时修复两个错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句