简体   繁体   English

绑定仅在断言中出现的类型变量

[英]Binding type variables that only occur in assertions

I find it extremely difficult to describe my problem, so here goes nothing: 我发现很难描述我的问题,所以什么也没做:

I have a bunch of assertions on the type of a function. 我对函数的类型有很多主张。 These assertions rely on a type variable that is not used for any parameter of the function, but is only used for internal bindings. 这些断言依赖于类型变量,该类型变量不用于函数的任何参数,而仅用于内部绑定。 Whenever I use this function it does not compile because, of course, the compiler has no information from which to guess what type to bind my type variable. 每当我使用此函数时,它都不会编译,因为,当然,编译器没有信息可用来猜测绑定我的类型变量的类型。 Here is the code: 这是代码:

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances,
  UndecidableInstances, FlexibleContexts, EmptyDataDecls, ScopedTypeVariables,
  TypeOperators, TypeSynonymInstances #-}

class C a a'  where convert :: a -> a'
class F a b   where apply :: a -> b
class S s a   where select :: s -> a

data CInt = CInt Int

instance S (Int,String) Int where select (i,_) = i
instance F Int CInt where apply = CInt

f :: forall s a b . (S s a, F a b) => s -> b
f s = 
  let v = select s :: a
      y = apply v :: b
  in y

x :: Int
x = f (10,"Pippo")

And here is the generated error: 这是生成的错误:

FunctorsProblems.hs:21:4:
    No instances for (F a Int, S (t, [Char]) a)
      arising from a use of `f' at FunctorsProblems.hs:21:4-17
    Possible fix:
      add an instance declaration for (F a Int, S (t, [Char]) a)
    In the expression: f (10, "Pippo")
    In the definition of `x': x = f (10, "Pippo")
Failed, modules loaded: none.
Prelude>

You are trying to intersect some set of instances of classes and for compiler there is no way to say that this intersection will be empty or single entry. 您正在尝试相交一些类实例集,对于编译器,没有办法说相交将为空或单个条目。
You want to force compiler to choose the right type for you without knowing which problems (information loss or complexity of calculations) that decision can bring in your program. 您想强迫编译器为您选择正确的类型,而又不知道该决定会带来哪些问题(信息丢失或计算复杂)。 If you want to do that you should give a hint to compiler what is the best type "a" for specific pair "s" and "b" (with us of that FunctionalDependencies you specified). 如果要这样做,则应向编译器提示,对于特定的“ s”和“ b”对(与您指定的那个FunctionalDependency一起使用),最佳类型“ a”是什么。

class E x a | x -> a
instance (S s Int, F Int CInt) => E (s, CInt) Int
f :: forall s a b . (E (s,b) a) => s -> b

Probably there is the way to specify order of preferred types of "a" for pair of "s" and "b" with further deduce of best "a" (ie use of type-level or something like that to attach that information). 可能存在一种方法,可以为“ s”和“ b”对指定“ a”的首选类型的顺序,并进一步推导出最佳的“ a”(即使用类型级别或类似的东西来附加该信息)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM