【发布时间】:2013-02-13 10:12:15
【问题描述】:
我正在 Haskell 中为 Coursera 的 AI 规划课程编写一个 AI General Problem Solver,而 ghci 抱怨一个模棱两可的类型变量。这是 Haskell 代码和我得到的错误:
-- 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) -
你有一个类型变量 t 用于类求解器,但它在任何地方都没有使用。也许你可以删除它,看看会发生什么。顺便说一句,你真的需要 ScopedTypeVariables 的东西吗?