小编won*_*nce的帖子

Haskell ad hoc多态性

我试图了解haskell中的ad-hoc多态性,即具有相同的函数为不同的参数类型提供不同的行为.

但是,以下测试代码编译

{-# LANGUAGE MultiParamTypeClasses #-}

class MyClass a b where
    foo :: a -> b

instance MyClass Bool Int where
    foo True = 0
    foo False = 1

instance MyClass Double Double where
    foo x = -x
Run Code Online (Sandbox Code Playgroud)

如果我尝试使用类似的东西来调用它

foo True
Run Code Online (Sandbox Code Playgroud)

ghci对我大吼:

No instance for (MyClass Bool b0) arising from a use of `foo'
The type variable `b0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there is a potential instance available:
  instance MyClass …
Run Code Online (Sandbox Code Playgroud)

polymorphism haskell overloading typeclass

4
推荐指数
2
解决办法
445
查看次数

使 Rust 中的迭代器之间复制的函数尽可能通用的正确数据类型是什么?

我通常需要在两个可迭代对象之间复制数据。除了slices特殊情况,我在标准库中没有找到合适的函数,所以我尝试自己写一个:

fn copy(source: /* ? */, target: /* ? */) {
    for (s, t) in source.zip(target) {
        *t = s.clone();
    }
}
Run Code Online (Sandbox Code Playgroud)

使该函数尽可能通用的数据类型的正确选择是什么?

types iterator rust

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

标签 统计

haskell ×1

iterator ×1

overloading ×1

polymorphism ×1

rust ×1

typeclass ×1

types ×1