标签: generic-function

Typescript - 如何缩小 switch 语句中泛型类型的类型可能性?

我正在尝试编写一个函数,该函数将根据传递的密钥和参数执行特定的计算。我还想强制传递的键和参数之间的关系,因此我使用了带有约束的通用函数:

interface ProductMap {
  one: {
    basePrice: number;
    discount: number;
  },
  two: {
    basePrice: number;
    addOnPrice: number;
  }
}

function getPrice<K extends keyof ProductMap>(key: K, params: ProductMap[K]) {
  switch (key) {
    case 'one': {
      return params.basePrice - params.discount; // Property 'discount' does not exist on type 'ProductMap[K]'.
    }
    case 'two': {
      return params.basePrice + params.addOnPrice;
    }
  }
}

Run Code Online (Sandbox Code Playgroud)

也许我以错误的方式思考这个问题,但似乎打字稿应该能够缩小 switch 语句中的泛型类型。我能让它工作的唯一方法就是克服这种尴尬:

function getPrice<K extends keyof ProductMap>(key: K, params: ProductMap[K]) {
  switch (key) {
    case 'one': {
      const p = params …
Run Code Online (Sandbox Code Playgroud)

generic-function typescript

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

试着学习:LISP中的对象重定向和通用函数!

我正在阅读实用的常见Lisp作为另一个问题的结果.

我刚刚阅读了第16章和第17章,您可以在其中找到LISP如何管理对象.但经过几年思考Java如何管理对象,我似乎无法理解如何使用CLOS在LISP中实现更大的架构.

所以我问你们大约20-50页关于CLOS应用于更大的架构而不是简单的例子.也许是一些博客或甚至经历!

TY

lisp common-lisp clos generic-function

6
推荐指数
3
解决办法
677
查看次数

Haskell中是否有任何通用的Hashable类型类?(又名"衍生(Hashable)")

是否有人编写了通用函数,以便hash可以自动为自定义数据类型生成函数(使用该deriving机制)?有几次,我写了以下类型的样板,

data LeafExpr = Var Name | Star deriving (Eq, Show)
instance Hashable LeafExpr where
    hash (Var name) = 476743 * hash name
    hash Star = 152857
Run Code Online (Sandbox Code Playgroud)

这可以自动生成:基本思想是每当添加数据时,您乘以素数,例如使用列表,

hash (x:xs) = hash x + 193847 * hash xs
Run Code Online (Sandbox Code Playgroud)

基本上,我想写的是

data LeafExpr = ... deriving (Hashable)
Run Code Online (Sandbox Code Playgroud)

编辑1

感谢所有非常有帮助的回复,每个人.当我有时间时,我会尝试添加一个通用方法作为练习.现在(也许sclv指的是什么?),我意识到我可以编写稍好的代码,

instance Hashable LeafExpr where
    hash (Var name) = hash ("Leaf-Var", name)
    hash Star = hash "Leaf-Star"
Run Code Online (Sandbox Code Playgroud)

编辑2

使用ghc,乘以随机素数比编辑1中的tupling好得多.与Data.HashTable的冲突从95%(非常糟糕)变为36%.代码在这里:[ http://pastebin.com/WD0Xp0T1 ] [ http://pastebin.com/Nd6cBy6G ].

haskell hash-function typeclass generic-function

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

专注于矢量和矩阵

我正在使用common-lisp进行实时图形实验,到目前为止它已经很棒了.我对速度的要求和与cffi的轻松兼容意味着我正在使用'typed'数组.代码中真正令人感到难看的一个区域是我的矩阵和矢量数学函数的泛型版本.由于CLOS无法专注于数组的长度,我正在做这样的事情:

(defun v+ (vec-a vec-b)
   (%v+ vec-a vec-b (length a) (length b)))

(defmethod %v+ (va vb (la (eql 3)) (lb (eql 3)))
   ***CODE HERE***)
Run Code Online (Sandbox Code Playgroud)

这有效,但感觉不对.我已经看到了各种CL实现的扩展,并听说了MOP的承诺.

我已经避开了这个,因为我担心它会破坏一些CL实现的功能,但我最近看到了Closer-to-Mop项目.

核心问题: MOP是否提供了一种更有效的长度专业化方法?我应该关注哪些领域/技术?

common-lisp clos generic-function mop

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

如何预测随机和固定效应模型?

我最近刚做从STATA于R的改变,并有一些麻烦实施将R等价的命令,STATA xtlogit,fe or repredict.我可以请求一些帮助来调整以下场景:

  data <- read.table("http://people.stern.nyu.edu/wgreene/Econometrics/healthcare.csv",header=TRUE, sep=",", na.strings="NA", dec=".", strip.white=TRUE)

   require(caret) # for confusionMatrix

   #### subset into test & train according to the panel nature (split  individuals rather then observations)
   nID <- length(unique(data$id))
   p = 0.50# partition

   inTrain <- sample(unique(data$id), round(nID * p), replace=FALSE)

   training <- data[data$id %in% inTrain, ] 

   testing <- data[!data$id %in% inTrain, ] 


   pooled <- glm(WORKING~WHITEC+FEMALE+BLUEC+HHNINC+AGE+AGESQ+EDUC+DOCVIS,data=training, family=binomial(link="logit"))

   prediction.working= round(predict(pooled,newdata=testing,type="response"))

   confusionMatrix(prediction.working,testing$WORKING) # Accuracy between both
Run Code Online (Sandbox Code Playgroud)

另外,我想对随机效果和固定效果做这些程序.所以我首先尝试了随机效果:

   library(glmmML)
   RE <- glmmML(WORKING~WHITEC+FEMALE+BLUEC+HHNINC+AGE+AGESQ+EDUC+DOCVIS, family=binomial(link="logit"), data=training, cluster=id, method="ghq", …
Run Code Online (Sandbox Code Playgroud)

r generic-function predict glm

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

如何使用"take"字作为CLOS泛型

泛型似乎提供了一个很好的工具来提取一个常用词并让它根据你传递的类型对事物起作用,事后可扩展性.

但是,已经采用并且没有定义为通用的常用词呢?如果我尝试定义REMOVE,例如:

(defclass reticulator () (splines))

(defmethod remove ((item reticulator)
     sequence &key from-end test test-not start end count key))
Run Code Online (Sandbox Code Playgroud)

我在SBCL中收到错误:

COMMON-LISP:REMOVE已经命名普通函数或宏.

这些内置函数之一是否有成语或通用的"通用ify"方式?人们这样做吗?

只是为了看看会发生什么我尝试使用泛型覆盖REMOVE:

(defgeneric remove (item sequence &key from-end test test-not start end count key))
Run Code Online (Sandbox Code Playgroud)

警告:重新定义COMMON-LISP:DEFGENERIC中的REMOVE

我不知道是否有一个"好"的方法,这将导致旧的实现,允许重载特定类型,希望赋予新的含义.

lisp common-lisp clos generic-function

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

从具有'this'的基类调用时,泛型函数参数的参数类型是什么?

令人困惑的问题,我知道.鉴于以下内容:

    class Test
    {
        public static void GenericFunc<T>(T SomeType)
        {
            System.Console.WriteLine("typeof(T): " + typeof(T).Name);
            System.Console.WriteLine("SomeType.GetType(): " + SomeType.GetType().Name);
        }
    }

    public class BaseType
    {
        public void RunTest() { Test.GenericFunc(this); }
    }

    public class DerivedType : BaseType { }
Run Code Online (Sandbox Code Playgroud)

以下代码生成有趣的输出:

    DerivedType Derived = new DerivedType();
    Derived.RunTest();

    // output:
    // typeof(T): BaseType
    // SomeType.GetType(): DerivedType
Run Code Online (Sandbox Code Playgroud)

但是,这表现得如我所料:

    Test.GenericFunc(new Derived());

    // output:
    // typeof(T): DerivedType
    // SomeType.GetType(): DerivedType
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助我理解这里的机制导致T在第一种情况下被评估为BaseType吗?

提前致谢!

c# inheritance generic-function

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

'show'是正常的S4泛型函数吗?

我正在尝试为我的类创建一个方法,该方法继承自data.frame.我本来希望只是从data.frame继承'show'方法,但我也可以编写自己的方法.我将我的类和'show'方法定义如下:

setClass("SCvec", representation(auth = "character",
    dev = "character",
    sensor = "character",
    channel = "character",
    starttime = "character",
    endtime = "character"),
    contains="data.frame")
setMethod("show", signature(x="SCvec"), function(x) print(x))
Run Code Online (Sandbox Code Playgroud)

当我输入showR控制台时,它会输出:

从包"方法"定义的"show"的standardGeneric

function (object) 
standardGeneric("show")
<bytecode: 0x0396bee8>
<environment: 0x0393ab60>
Methods may be defined for arguments: object
Use  showMethods("show")  for currently available ones.
(This generic function excludes non-simple inheritance; see ?setIs)
Run Code Online (Sandbox Code Playgroud)

所以看起来我不需要自己使用StandardGeneric()将它变成泛型.但是当我运行我的setMethod("show", signature(x="SCvec"), function(x) print(x))线路时,我得到了错误

Error in match.call(definition, call, expand.dots) : 
  unused argument(s) (x = c("SCvec", ""))
Run Code Online (Sandbox Code Playgroud)

我已经定义了这个方法,就像我定义任何其他方法一样.为什么这个方法定义不起作用?'show'与其他通用函数不同吗?

r show generic-function s4

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

用普通函数替换普通函数

我想使用elt,nth和mapcar之类的名称来创建一个我正在进行原型设计的新数据结构,但这些名称指定了普通函数,因此,我认为需要重新定义为泛型函数.

据推测,重新定义这些名称是不好的形式?

有没有办法告诉defgeneric不生成程序错误并继续替换功能绑定?

这些不是通用功能还是历史性的,有充分的理由吗?

请问这里考虑的智慧和最佳做法是什么?

common-lisp clos generic-function

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

如何实现泛型函数的专用版本?

我想要为其参数类型优化一个函数的多个版本,并根据上下文调用适当的函数.

在我的例子中,所有参数都具有相同的类型,并且都是等价的,因此它宁可避免使用self参数.

试过这段代码:

trait Foo<T> { 
    fn foo(a: T, b: T, c: T); 
}

impl Foo<i32> {
    fn foo(a: i32, b: i32, c: i32) {}
}

impl Foo<i16> {
    fn foo(a: i16, b: i16, c: i16) {}
}

fn main() {
    Foo::foo(1i32,2,3);
    Foo::foo(1i16,2,3);
}
Run Code Online (Sandbox Code Playgroud)

但Rust需要类型注释:

错误:需要输入注释:无法解析_ : Foo<i32>[E0283]

我可以避免在呼叫站点提供类型注释吗?如果必须,怎么办?

traits specialization generic-function rust

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