小编JSQ*_*reD的帖子

如果类实例可用,请使用专门的实现

考虑以下情况:

slow_func :: Eq a  => [a] -> [a]
fast_func :: Ord a => [a] -> [a]
Run Code Online (Sandbox Code Playgroud)

我有两个功能,slow_funcfast_func.这些函数是同一个抽象函数的不同实现(它们做同样的事情),但是一个比另一个快.只有在a可以订购类型时才能实现更快的实施.有没有办法构建一个fast_func尽可能充当的函数,并以slow_func其他方式恢复?

as_fast_as_possible_func :: Eq a => [a] -> [a]
Run Code Online (Sandbox Code Playgroud)

我已经尝试过以下方法:

{-# LANGUAGE OverlappingInstances  #-}

class Func a where
    as_fast_as_possible_func :: [a] -> [a]

instance Ord a => Func a where
    as_fast_as_possible_func = fast_func

instance Eq a => Func a where
    as_fast_as_possible_func = slow_func
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不会编译,生成以下错误:

Duplicate instance declarations:
  instance Ord a => Func a …
Run Code Online (Sandbox Code Playgroud)

haskell types typeclass

16
推荐指数
2
解决办法
716
查看次数

为什么我们不能设置属性的属性?

我经常发现自己想要沿着这些方向做点什么:

Form form = new Form();
form.ClientSize.Width = 500;
Run Code Online (Sandbox Code Playgroud)

当然编译器现在会抱怨此代码无效,因为ClientSize是属性,而不是变量.

我们可以通过完整设置ClientSize来解决这个问题:

form.ClientSize = new Size(500, ClientSize.Height);
Run Code Online (Sandbox Code Playgroud)

或者,一般情况下:

Size s = form.ClientSize;
s.Width = 500;
form.ClientSize = s; //only necessary if s is a value-type. (Right?)
Run Code Online (Sandbox Code Playgroud)

但这看起来都是不必要的,也是模糊不清的.为什么编译器不能为我做这个?当然,我问的是一般情况,可能涉及更深层次的属性,而不仅仅是上面的世俗例子

基本上,我问为什么没有语法糖将该行form.ClientSize.Width = 500转换为上述代码.这只是一个尚未实现的功能,它是为了避免来自不同的getter和setter的副作用的堆叠,以防止在没有定义其中一个setter时产生混淆,或者是否存在完全不同的原因这不存在?

c# language-design properties

6
推荐指数
1
解决办法
182
查看次数

初始化时多个用户定义的转换

我知道 C++ 在类型之间转换时只允许单个用户定义的隐式转换。然而,我最近遇到了一种情况,似乎在初始化时允许双重用户定义的隐式转换

考虑以下类:

//fractions
class Rational {
public:
    int num, den;
    // default constructor, etc.
    Rational(int n) : num(n), den(1) {} // NOT explicit
    // arithmetic and compound assignment defined between two Rational's.
};

//numbers of the form a + b sqrt(N), where a, b are of type R
template<typename R, int N>
class RingExtension {
public:
    R a, b;
    // default constructor, etc.
    RingExtension<R, N>(R a) : a(a), b(0) {} // NOT explicit
    // arithmetic and …
Run Code Online (Sandbox Code Playgroud)

c++ standards-compliance type-conversion visual-c++ implicit-conversion

5
推荐指数
1
解决办法
222
查看次数

声明具有完整定义的子类

我正在尝试执行以下操作:

-- enum which wraps arround
class (Enum a, Bounded a) => CyclicEnum a where
    next, prev :: a -> a

-- for equatable types this is readily implemented
instance (Enum a, Bounded a, Eq a) => CyclicEnum a where
    next x | x == maxBound = minBound
           | otherwise     = succ x

    prev x | x == minBound = maxBound
           | otherwise     = pred x
Run Code Online (Sandbox Code Playgroud)

但是除非我同时启用FlexibleInstances和UndecidableInstances,否则这不会编译,这似乎不对.什么是正确的方法(即,通常使用的方法,最好没有语言扩展)来做这样的事情?有吗?

haskell typeclass

3
推荐指数
1
解决办法
62
查看次数