使[(Matrix Double,Vector Double)]成为Num的实例 [英] make [(Matrix Double,Vector Double)] an instance of Num

查看:55
本文介绍了使[(Matrix Double,Vector Double)]成为Num的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了:

type Network = [(Matrix Double,Vector Double)]

其中Matrix和Vector来自hmatrix库.从hmatrix的文档中,在我看来Matrix Double和Vector Double已经是Num的实例.由于我需要增加和减少Networks的安静程度,因此我也希望Network成为Num的一个实例.我尝试过

where Matrix and Vector are from the hmatrix library. From the documentation of hmatrix it seems to me that Matrix Double and Vector Double are already instances of Num. Since I need to add and subtract Networks quiet a lot I also want Network to be an instance of Num. I tried

instance Num Network where
  (+) = zipWith (\(m,v) (n,w) -> (m+n,v+w))
  (-) = zipWith (\(m,v) (n,w) -> (m-n,v-w))
  (*) = zipWith (\(m,v) (n,w) -> (m*n,v*w))

但是我遇到了错误:非法实例声明.

but I am getting the error : Illegal Instance declaration.

推荐答案

Alexis King的注释对正确编译当前代码是正确的.但是,最好为 Network 创建一个 newtype -这样,您根本就不需要使用任何语言扩展.

Alexis King's comment is correct to get your current code to compile. However, it might be better practice to make a newtype for Network - that way you don't need to use any language extensions at all.

newtype Network = Network [(Matrix Double,Vector Double)]

instance Num Network where
  (Network n1) + (Network n2) = Network $ zipWith (\(m,v) (n,w) -> (m+n,v+w)) n1 n2
  (Network n1) - (Network n2) = Network $ zipWith (\(m,v) (n,w) -> (m-n,v-w)) n1 n2
  (Network n1) * (Network n2) = Network $ zipWith (\(m,v) (n,w) -> (m*n,v*w)) n1 n2

这篇关于使[(Matrix Double,Vector Double)]成为Num的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆