haskell - How to use replicateM? -
i started learning code haskell apologies if stupid question. trying redo 8 queen problem making use of [] monad. here code,
import control.monad addqueen :: [int] -> [[int]] addqueen xs = [x:xs|x<-[1,2..8], not $ x `elem` xs || (any (\(index,q) -> abs (x-q) ==index) $ zip [1..] xs)]
when try to
[[]]>>= replicatem 8 addqueen
it not work yields following error:
couldn't match expected type `t0 -> t1' actual type `[[a0]]' first argument of ($) takes 1 argument, type `[[a0]]' has none in expression: [[]] >>= replicatem 8 $ addqueen in equation `it': = [[]] >>= replicatem 8 $ addqueen
so how achieve want here?
replicatem
wrong choice here:
prelude control.monad> :t replicatem replicatem :: (monad m) => int -> m -> m [a] prelude> let addqueen :: [int] -> [[int]]; addqueen [] = undefined
this means in expression replicatem 8 addqueen
, m ~ ([int] -> [[int]])
i.e. m ~ ((->) [int])
, a ~ [[int]]
. , type m [a] ~ ([int] -> [[[int]]])
. not intended.
(if type error "no instance (monad ((->) [int]))
", try loading e.g. control.applicative
first, bring in definition instance monad ((->) r)
. happen if you're using older version of ghc).
try this, instead:
prelude> :m +control.monad prelude control.monad> :t (>=>) (>=>) :: (monad m) => (a -> m b) -> (b -> m c) -> -> m c prelude control.monad> :t foldl1 (>=>) $ replicate 8 addqueen foldl1 (>=>) $ replicate 8 addqueen :: [int] -> [[int]] prelude control.monad> :t [[]] >>= ( foldl1 (>=>) $ replicate 8 addqueen ) [[]] >>= ( foldl1 (>=>) $ replicate 8 addqueen ) :: [[int]]
update: expression, x1 = foldl1 (>=>) $ replicate 8 addqueen
, stands on own, in prolog terms corresponding a "goal" of adding 8 queens initial solution. uses above-basic-level operator "fish"1 i.e. left-to-right kleisli composition operator >=>
, defined that
(m >>= a) >>= b === m >>= (a >=> b)
i.e. >=>
composition operator monadic functions. use x1
feeding empty solution it, [ [] ] >>= x1
.
the expression given in comments sassa nf, x2 = foldl (>>=) [[]] $ replicate 8 addqueen
, uses basic monadic bind operator >>=
, works whole.
1 http://haskellrescue.blogspot.com/2011/03/cooking-delicious-fish.html
Comments
Post a Comment