在Haskell中建模循环调度程序时的非法数据类型上下文

时间:2012-12-06 12:36:19

标签: haskell typeclass algebraic-data-types

我在Haskell中建模循环调度程序。

class Schedulable s where
  isFinal :: s -> Bool

class Scheduler s where
  add :: (Schedulable a) => a -> s -> s
  next :: (Schedulable a) => s -> (a, s)
  empty :: s -> Bool

data Schedulable a => RoundRobin = RoundRobin [a] [a]

instance Scheduler RoundRobin where
  add p (RoundRobin ps qs) = RoundRobin (ps ++ [p]) qs

  next (RoundRobin []     qs) = next (RoundRobin qs [])
  next (RoundRobin (p:ps) qs) = (p, RoundRobin ps (qs ++ [p]))

  empty (RoundRobin [] _) = True
  empty _                 = False

然而,GHC抱怨说

main.hs:9:6:
    Illegal datatype context (use -XDatatypeContexts): Schedulable a =>

我该如何解决这个问题?

我也看到了a proposal about removing datatype contexts,那么如何在不使用数据类型上下文的情况下对调度程序进行建模?

2 个答案:

答案 0 :(得分:6)

您的Scheduler班级

class Scheduler s where
  add :: (Schedulable a) => a -> s -> s
  next :: (Schedulable a) => s -> (a, s)
  empty :: s -> Bool

不起作用。

add承诺可以将任何Schedulable类型的值添加到调度程序中。这是可能的,但它需要扩展名,ExistentialQuantificationGADTs将允许定义包含任何 Schedulable值的类型。

然而,

next承诺提供任何 Schedulable类型的值,无论调用者想要什么,这都不会起作用。如果我只将Int值添加到调度程序中,然后请求String,它将如何凭空构建一个?

让代码工作的一种方法是

{-# LANGUAGE GADTs #-}
module Schedules where

class Schedulable s where
  isFinal :: s -> Bool

class Scheduler s where
  add :: (Schedulable a) => a -> s -> s
  next :: s -> (Schedule, s) -- returns a Schedulable item of unknown type, wrapped in a Schedule
  empty :: s -> Bool

-- Wrapper type for any Schedulable
data Schedule where
    Schedule :: Schedulable a => a -> Schedule

-- Equivalent alternative using existential quantification instead of GADT syntax
-- data Schedule = forall a. Schedulable a => Schedule a

-- make Schedules Schedulable, maybe not necessary
instance Schedulable Schedule where
    isFinal (Schedule s) = isFinal s

-- RoundRobin queues schedulable items, wrapped as Schedules, since lists are homogeneous
data RoundRobin = RoundRobin [Schedule] [Schedule]

-- How RoundRobin works
instance Scheduler RoundRobin where
  -- enqueue item after wrapping it
  add p (RoundRobin ps qs) = RoundRobin (ps ++ [Schedule p]) qs

  -- deliver next item to process
  -- the first equation suggests that (Maybe Schedule, s) would be the better return type
  next (RoundRobin []     []) = error "Nothing to schedule"
  next (RoundRobin []     qs) = next (RoundRobin qs [])
  next (RoundRobin (p:ps) qs) = (p, RoundRobin ps (qs ++ [p]))

  empty (RoundRobin [] _) = True
  empty _                 = False

使用GADT语法或存在量化使得通过模式匹配对构造函数施加的约束可用,与旧的DatatypeContexts相反,尽管存在类型约束,但需要将上下文放在函数上使用类型。

答案 1 :(得分:3)

不建议将约束定义到data定义中(参见Learn Haskell...)。

最好将约束设置为函数。

(无论如何,你可以设置DatatypeContexts修饰符)