我在Coursera的AI Planning課程中爲Haskell編程的AI常規問題解決程序,ghci抱怨模糊的類型變量。這裏是Haskell代碼和我得到的錯誤:在Haskell中編寫AI Solver時模糊的類型變量
-- Solver.hs
{-# LANGUAGE GADTs,FlexibleInstances,UndecidableInstances,ScopedTypeVariables,TypeFamilies,MultiParamTypeClasses #-}
module Solver
(Solver,State,Transition)
where
class (Show t,Eq t) => Transition t where
transition :: State s => s -> t -> s
class (Show s,Eq s) => State s where
getPossibleTransitions :: Transition t => s -> [t]
isStateValid :: s -> Bool
isGoalState :: s -> Bool
class Solver s t where
getPossibleNextStates :: s -> [s]
isStateVisited :: [s] -> s -> Bool
getNextFringeStates :: [s] -> [[s]]
--getNextGeneration :: [s] -> [s] -> [s]
flatten :: [[a]] -> [a]
flatten [] = []
flatten listOfLists = (head listOfLists) ++ (flatten (tail listOfLists))
instance (State s,Transition t) => Solver s t where
getPossibleNextStates (state::s) =
filter isStateValid (map transitionFunction possibleTransitions)
where
transitionFunction = (transition state)::(t -> s)
possibleTransitions = (getPossibleTransitions state)::([t])
isStateVisited visitedStates state =
any (== state) visitedStates
getNextFringeStates (states::[s]) =
map (getPossibleNextStates :: (s -> [s])) (states::[s])
-- COMPILATION:
{-
Prelude> :l Solver.hs
[1 of 1] Compiling Solver (Solver.hs, interpreted)
Solver.hs:38:8:
Ambiguous type variable `t0' in the constraint:
(Transition t0) arising from a use of `getPossibleNextStates'
Probable fix: add a type signature that fixes these type variable(s)
In the first argument of `map', namely
`(getPossibleNextStates :: s -> [s])'
In the expression:
map (getPossibleNextStates :: s -> [s]) (states :: [s])
In an equation for `getNextFringeStates':
getNextFringeStates (states :: [s])
= map (getPossibleNextStates :: s -> [s]) (states :: [s])
Failed, modules loaded: none.
-}
我無法弄清楚任。 (但僅供參考,你的'flatten'函數實際上等同於Prelude中的'concat') – 2013-02-13 10:36:42
你有一個用於類求解器的類型變量t,但它並沒有用到。也許你可以刪除它,看看會發生什麼。順便說一句,你真的需要ScopedTypeVariables的東西嗎? – Ingo 2013-02-13 11:12:36