'워드 체인'을 생성하는 프로그램을 작성하려고합니다. bat -> cat -> cot -> bot, 모나드 (대부분은 이해력)를 사용하여 단어의 조합을 생성하고, 상태 모나드를 사용하여 가능성을 탐색합니다. 나는 단어가 작동 아래,하지만 당신은 내가 정말이 부분에서 뭘하는지 모르는 볼 수 생성모나드 관련 문제
import Control.Monad.State
type Word = String
type Chain = [Word]
getNext :: Word -> State Chain Word
getNext word = do
list <- get
return (list ++ "current word")
부분 : 그 두 번째 부분은 나에게 문제를주고있다. 기본적으로 wordVariations :: Word -> [Word]
은 Word를 사용하고 주어진 단어와 한 문자가 다른 단어 목록을 반환합니다. 나는 각 단어가 선행자를 나타내는 상태가되도록 이것을 바꾸려고한다.
예 : input = "cat".
3 단계 후에 "cat"에서 "got"을 얻을 수 있지만, "cat", "cot", "got" 어떻게 거기에 도착했는지 말해줘.
내가 온라인에서 찾은 State Monad 튜토리얼은 전혀 도움이되지 않았습니다. 위의 코드는, GHC 컴파일 할 때 오류 제공 : 이것은 단지의 떨어져 작동하기위한 테스트로 의미
WordChain.hs:42:11:
Couldn't match type `Word' with `Char'
When using functional dependencies to combine
MonadState s (StateT s m),
arising from the dependency `m -> s'
in the instance declaration in `Control.Monad.State.Class'
MonadState [Char] (StateT Chain Data.Functor.Identity.Identity),
arising from a use of `get' at WordChain.hs:42:11-13
In a stmt of a 'do' block: list <- get
In the expression:
do { list <- get;
return (list ++ "current word") }
Failed, modules loaded: none.
을,하지만 난 그것을 알아낼 수 없습니다!
코드는 다음과 같이 유용합니다. 이것이 이것이 가장 현명한 방법이 아닐 수도 있지만, 모나드에 대해 배울 수있는 좋은 기회입니다. 나는 몇 가지 주요 리팩토링이 요구 될 것이라고 생각하기 때문에 내가 코드도 작동하는 방식에서 필요한 변경을 열어주는 말들 : 모든
import Control.Monad.State
type Word = String
type Dict = [String]
-- data Chain = Chain [Word] deriving (Show)
replaceAtIndex :: Int -> a -> [a] -> [a]
replaceAtIndex n item ls = a ++ (item:b) where (a, (_:b)) = splitAt n ls
tryLetter str c = [replaceAtIndex n c str | n <- [0..(length str - 1)]]
wordVariations str = tryLetter str =<< ['a' .. 'z']
testDict :: Dict
testDict = ["cat","cog","cot","dog"]
------- implement state to record chain
type Chain = [Word] -- [cat,cot,got,tot], etc. state var.
startingState = [""] :: Chain
getNext :: Word -> State Chain Word
getNext w = do
list <- get
return (list ++ "current word")
'getNext'가 주를 변경해야합니까? (어디에서 전혀 바뀌 었습니다) - 문제가 바로 있습니다 -이게 실제로 무엇을해야합니까? BTW : 왜 여기에 모든 상태 - 모나드가 필요하다고 생각하니? – Carsten