【问题标题】:How to add predicate to multiparam class in haskell?如何在haskell中向多参数类添加谓词?
【发布时间】:2013-01-06 18:26:06
【问题描述】:

GHC 抱怨此代码:

{-# LANGUAGE TypeFamilies, MultiParamTypeClasses, ScopedTypeVariables #-}

class Test a b where
    data Data a b
    data Marker a b
    test :: Marker a b -> Bool

work :: (Test a b, Test a2 b2) => Data a b -> Data a2 b2 
work =
    let (m :: Marker a2 b2) = undefined
    in if test m then undefined else undefined

带有消息:

You cannot bind scoped type variables `a2', `b2'
  in a pattern binding signature
In the pattern: m :: Marker a2 b2

我不想将work 函数的实际功能移动到Test 类中,因为test 谓词用于多个函数。

【问题讨论】:

    标签: haskell type-inference typeclass


    【解决方案1】:

    如果将类型变量带入作用域,它就会编译:

    work :: forall a b a2 b2. (Test a b, Test a2 b2) => Data a b -> Data a2 b2 
    work =
        let (m :: Marker a2 b2) = undefined
        in if test m then undefined else undefined
    

    如果没有显式的forall,let-binding 中的类型变量a2b2 是新的类型变量。

    【讨论】:

      【解决方案2】:

      forall a b a2 b2. 用作a2,Marker a2 b2 中的b2 将被视为新的。使用forall 会将它们纳入范围:

      work :: forall a b a2 b2. (Test a b, Test a2 b2) => Data a b -> Data a2 b2 
      

      更多关于forall keyword

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-22
        • 1970-01-01
        • 2013-04-08
        • 1970-01-01
        • 2012-09-09
        • 1970-01-01
        • 2018-09-20
        • 1970-01-01
        相关资源
        最近更新 更多