[英]What are the pitfalls of using FlexibleContexts and FlexibleInstances?
Since these flexible contexts and instances aren't available in the Haskell standard, I assume there are potential problems when using them. 由于Haskell标准中没有这些灵活的上下文和实例,因此我假设使用它们时存在潜在的问题。 What are they?
这些是什么? Can they lead to some ambiguity, undecidability, overlapping instances, etc.?
它们会导致一些模棱两可,不确定性,实例重叠等吗?
There is a similar question that asks only about FlexibleInstances
, not FlexibleContexts
, but the answer only says "that it's safe to use them". 有一个类似的问题 ,仅询问
FlexibleInstances
,而不询问FlexibleContexts
,但答案仅是“使用它们是安全的”。
I once stumbled upon the following. 我曾经偶然发现以下内容。 Answering this question , I first tried this code:
回答这个问题 ,我首先尝试了以下代码:
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
class (Eq a, Show a) => Genome a where
crossover :: (Fractional b) => b -> a -> a -> IO (a, a)
mutate :: (Fractional b) => b -> a -> IO a
develop :: (Phenotype b a) => a -> b
class (Eq a, Show a) => Phenotype a b | a -> b where
-- In case of Coevolution where each phenotype needs to be compared to
-- every other in the population
fitness :: [a] -> a -> Int
genome :: (Genome b) => a -> b -- here, the problem
breed parents cross mute = do
children <- mapM (\ (dad, mom) -> crossover cross (genome dad) (genome mom))
parents
let ch1 = map fst children ++ map snd children
mutated <- mapM (mutate mute) ch1
return $ map develop mutated
And got a compilation error and a suggestion by GHCi to add the FlexibleContexts
option. 并得到了编译错误和GHCi的建议以添加
FlexibleContexts
选项。 When I did, it compiled OK. 当我这样做时,它编译确定。 But this was actually not a right thing to do, as the constraint declaration introduced new scope for type variables, and
b
in genome
's type signature became completely unrelated to the one in the type class; 但这实际上不是正确的事,因为约束声明为类型变量引入了新的范围,并且
genome
类型签名中的b
变得与类型类中的类型完全无关; yet FlexibleContexts
provided a cover for this. 然而,
FlexibleContexts
为此提供了掩护。
With the constraint specified properly at the type class level, 在类型类级别正确指定约束后,
class (Eq a, Show a, Genome b) => Phenotype a b | a -> b where
-- In case of Coevolution where each phenotype needs to be compared to
-- every other in the population
fitness :: [a] -> a -> Int
genome :: a -> b
it passed compilation without requiring the FlexibleContexts
option. 它通过了编译,而不需要
FlexibleContexts
选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.