隐式转换:比动态类型更强大?

  本文内容主要来自[url=http://www.codecommit.com/blog/ruby/implicit-conversions-more-powerful-than-dynamic-typing]Implicit Conversions: More Powerful than Dynamic Typing?[/url],我只对其中一部分进行了翻译。
  隐式转换是[url=Haskell type classes]Scala[/url]中实现的一种类似于Haskell type classes的类型系统,它使得Scala这种静态类型的语言具有某些“动态”的特性。下面用具体例子来说明。

[color=red]案例1[/color]:[color=blue]给String添加一个reduce方法,其返回值为字符串中大写字母组成的新字符串。[/color]
在Scala中,最终效果如下:
//Scala
val acronym = "Microsoft Certified Systems Engineer".reduce
println(acronym) // MCSE

  由于String是Java语言内置的类型,现在遇到的问题是:在静态语言中,我们不能在运行时往已经存在的类中动态添加方法。
  在Scala中,我们可以定义一个新的类型,使它具有所需要的方法,然后再顶一个一个从已有类型到新类型的隐式转换。然后Scala编译器将会在幕后实施其魔法。代码如下:
class MyStr(str:String) {
def reduce = str.foldLeft(""){ (s,c) =>
if(c.isUpperCase) s+c else s
}
}

implicit def str2MyStr(str:String) = new MyStr(str)


作为对照,我们看看在Ruby中的实现:
class String
def reduce
arr = unpack('c*').select { |c| (65..90).include? c }
arr.pack 'c*'
end
end

puts 'HyperText Transfer Protocol'.reduce # HTTP



[color=red]案例2[/color]:[color=blue]一个稍微复杂一点的问题:重载整数类型的[/color][color=red]<[/color][color=blue]操作符,使得它能与String比较,并且但String的长度小于该整数时返回true,否则返回false[/color]
  在Scala中,同样可以通过隐式转换机制来解决该问题。这一次我们使用比上面更简洁的形式:
//Scala,that's all
implicit def lessThanOverload(i: Int) = new {
def <(str: String) = str.length < i
}

  下面我们看看Ruby中如何解决这个问题,一个很自然的想法是玩Fixnum中添加所需的方法:
class Fixnum
def <(str)
str.size < self
end
end

  很不幸的是,这个看起来很对的方法是行不通的。每次调用整数的<操作符时都会进入一个死循环并很快导致堆栈溢出。
  我们可以将方法改写成如下以避免这个问题:
class Fixnum
def <(str)
self >= str.size
end
end

  这次不用担心堆栈溢出了,但新的问题出现了:
[quote]irb(main):006:0> 123 < 'test'
=> true
irb(main):007:0> 123 < 123
=> true[/quote]
  这个问题的最终Ruby解法是这样的:
class Fixnum
alias_method :__old_less_than__, '<'.to_sym
def <(target)
if target.kind_of? String
__old_less_than__ target.size
else
__old_less_than__ target
end
end
end

  囧,相比Scala,Ruby的解决方法显得即冗长且丑陋。
16、Scala 隐式转换与类型类模式深度解析 本文深入解析了 Scala 中的隐式转换与类型类模式,探讨了它们在解决表达式问题、扩展现有类功能以及实现即席多态方面的应用。文章详细介绍了隐式转换的工作原理、技术问题、Scala 内置的隐式转换以及相关的最佳实践。通过示例代码,展示了如何使用隐式类实现 toJSON 方法、处理异构类型列表以及实现 Scala 与 Java 类型的互操作性。此外,还总结了隐式转换的优缺点,并提供了在实际开发中使用隐式转换的决策流程图和 mermaid 示例。 阅读详情

相关推荐

C++中动态类型转换与类型识别的正确使用

本文探讨了C++中动态类型转换(dynamic_cast)与类型识别(RTTI)的使用,包括其与static_cast、reinterpret_cast、const_cast和typeid操作符的区别和联系。通过代码示例和详细解释,深入解析了如何在保持类型安全的同时实现基类和派生类指针间的转换,以及如何利用RTTI机制获取对象类型信息。

weixin_35751412的博客 461

PostgreSQL类型转换实战:从CAST到隐式转换的5个常见场景解析

本文深入解析PostgreSQL类型转换的5个常见实战场景,涵盖从显式CAST到隐式转换的应用技巧与潜在陷阱。通过电商订单处理、数据迁移、API响应处理等实际案例,帮助开发者掌握pg类型转换的最佳实践,提升数据库操作效率与数据准确性。

weixin_28347369的博客 183

win10下Miracast无线投屏使用教程及异常解决方案(超详细)

文章目录一、什么是Miracast?二、主流的无线投屏技术有哪些特点?三、如何查看自己的win10电脑是否支持Miracast无线投屏功能?四、win10电脑如何使用Miracast无线投屏功能? 一、什么是Miracast? Miracast是由Wi-Fi联盟于2012年所制定,以Wi-Fi直连(Wi-Fi Direct)为基础的无线显示标准。支持此标准的3C设备(如智能手机、电视、投影、电脑等...

帅气的小白的博客 44万+

Ruby中,实例方法可以隐式使用类变量,但是必须显式使用类方法

class C @@Const1=1 Const2=2 @@var3=3 def self.m p @@Const1,Const2,@@var3; end def m2 p @@Const1,Const2,@@var3; C::m #ok #m #error:undefined local variable or method `m'

lslxdx的专栏 1274

字节跳动高频111道核心前端面试题解析,web开发增强

但是本人觉得看书也很必要,可以节省很多时间,常见的javascript的书,例如:javascript的高级程序设计,是每位前端工程师必不可少的一本书,边看边用,了解js的一些基本知识,基本上很全面了,如果有时间可以读一些,js性能相关的书籍,以及设计者模式,在实践中都会用的到。内容包括html,css,JavaScript,ES6,计算机网络,浏览器,工程化,模块化,Node.js,框架,数据结构,性能优化,项目等等。自定义指令(v-check、v-focus)的方法有哪些?v-model是什么?

2401_84094620的博客 1207

TC264摄像头循迹进阶:八邻域与逐行遍历在复杂赛道边界提取中的实战对比

本文对比分析了TC264摄像头循迹中八邻域法与逐行遍历法在复杂赛道边界提取中的实战表现。八邻域法在边界连续性方面表现优异,适合处理环岛等复杂元素;逐行遍历法则在计算效率和岔路口识别上更具优势。文章提供了详细的代码实现和优化策略,帮助智能车竞赛选手根据赛道特点选择最佳算法方案。

rainy的博客 946

ruby不同数据类型之间的相互转换

ruby的整数、浮点数、字符串的类均提供了to_i,to_f,to_s三个方法 浮点数转换成整数,只保留整数部分 irb(main):138:0&gt; 3.5.8.to_i =&gt; 3 整数转换成浮点数,会添加小数点和0 irb(main):147:0&gt; 3.to_f =&gt; 3.0 整数转换成字符串,会加上双引号 irb(main):151:0&gt; 3.to...

我的祖传代码 3613

从SRIOV到SIOV:PCIe虚拟化技术下一代革命

如果说SR-IOV是过去十年PCIe虚拟化的“标杆方案”,那SIOV就是为超大规模云数据中心、AI集群量身打造的“破局者”——它解决了SR-IOV难以逾越的扩展性瓶颈,同时平衡了性能、成本与生态兼容性。今天就从“为什么需要SIOV”到“SIOV到底强在哪”,再到“未来要解决什么问题”,做一次全方位深度拆解。

存储随笔 2595

Java基础——隐式转换vs强制转换

在定义变量时,有许多要注意的问题,一不小心就会出现损失精度或者不兼容类型等问题。 例如:     1.定义长整型数据时,必须加后缀l或L               long l =123456789012345L     2.定义单精度类型时(7-8位有效数字),必须加后缀 f 或 F               float f = 12.5F           3. bo

贵宝的博客 2万+

嵌入式开发之瑞芯微RK356x--基本环境搭建

嵌入式环境搭建

NexyHO的博客 624

构建基于知识图谱的金融监管合规系统

金融行业是一个高度监管的领域,金融机构需要遵守众多复杂的法规和政策。传统的金融监管合规方式往往依赖于人工审查和简单的规则引擎,效率低下且容易出错。构建基于知识图谱的金融监管合规系统的目的在于利用知识图谱强大的知识表示和推理能力,实现对金融业务数据的自动化分析和合规检查,提高监管合规的效率和准确性。本系统的范围涵盖了金融机构的各类业务,如银行业务、证券业务、保险业务等。

AI天才研究院 1175

如何在老款 Mac 上安装新版 macOS:OpenCore Legacy Patcher 完整指南

2007 至 2017 年款的 Intel Mac 可借助 OpenCore Legacy Patcher 安装 macOS 11 至 macOS 15,并恢复原生 OTA 更新能力。 ## 你的设备能不能用 打开"关于本机"→"系统报告",查看"型号标识符"一项,再对照下方范围。若你的设备不在范围内,说明这条 Intel Mac 安装新版系统的路径对本工具不可用。 | 设备系列 | 支持年

gitblog_00007的博客 881

Linux内核驱动模型--PCIe(PCI Express)驱动​​

本文系统介绍了Linux内核中PCIe驱动的设计与实现。首先从架构定位入手,指出PCIe驱动基于PCI子系统扩展支持高速、低功耗特性。核心数据结构struct pci_driver包含设备匹配表id_table、生命周期函数probe/remove等关键组件。文章详细解析了驱动与设备的绑定流程、资源管理机制,并重点阐述了MSI-X中断、电源管理、热插拔和多队列等高级特性实现方案。最后提供了lspci、dmesg等调试工具的使用方法,总结了PCIe驱动在支持高性能设备中的关键作用。全文通过架构设计、核心结构、

amy_mhd的博客 438

JavaScript 中的弱类型,动态类型

JavaScript 是一门弱类型(weakly typed),动态类型(dynamically typed)的编程语言,其中它弱类型的特性让人又爱又恨,既带来了一些简洁的语法,在一定程度上提升了开发者的编码速度,也带来了一些坑,增加了项目维护的难度。本文介绍 JavaScript 中弱类型的一些体现方面,看看我们能如何更好的利用它。 编程语言的类型 编程语言可以被分为弱类型或强类型,静态类型或...

wsc2111的博客 2486

YOLOv11【第三章:高阶应用与落地篇·第7节】多任务联合训练(Multi-Task Learning):检测+分割+关键点三头并进!

🏆 本文收录于专栏 《YOLOv11实战:从入门到深度优化》。本专栏围绕 YOLOv11 的改进、训练、部署与工程优化 展开,系统梳理并复现当前主流的 YOLOv11 实战案例与优化方案,内容目前已覆盖 分类、检测、分割、追踪、关键点、OBB 检测 等多个方向。

**My Coding Family** 741

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

JavaScript弱类型:隐式转换与内存泄漏的“陷阱指南”

JavaScript 的弱类型特性是其灵活性和动态性的体现,但同时也为开发者在逆向工程和调试中带来了一些潜在的挑战。

爪巴虫 632

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

SystemVerilog | 永不缺席的话题:类型转换(Type Casting)

”永不缺席“绝不是一个夸大的形容词,即使是针对SystemVerilog这种具有硬件气质的语言。 数据类型的处理规则在编程中会影响很多东西,涉及变量安全、内存安全等,具体包括变量赋值、过程参数、函数调用和返回值。换句话说,但凡上手写代码,就逃不过数据类型的处理规则。 类型转换是数据类型处理规则中重要的一项,几乎每一种编程语言都有自家关于数据类型转换的规则。数据类型的转换有时候是隐式的(implicitly),有时候是显式的(explicitly),有些是编译阶段(compile-time)完成的,有些是运行

oldmoney 484

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Python 数据类型转换的内部机制与性能分析

``html Python 数据类型转换的内部机制与性能分析。

2501_91247610的博客 1523

C++中四种cast转换

C++中四种类型转换是:static_cast, dynamic_cast, const_cast, reinterpret_cast const_cast 用于将const变量转为非const static_cast 用于各种隐式转换,比如非const转const,void*转指针等, static_cast能用于多态向上转化,如果向下转能成功但是不安全,结果未知; dynamic_cast 用...

瞎子my的博客 2282

Q3:C++中的四种cast转换

static_cast、dynamic_cast、const_cast、reinterpret_cast

不积跬步无以至千里 231

Apache Groovy闭包编程终极指南:为什么它比Java Lambda更强大

Apache Groovy是一种功能强大的多范式编程语言,专为JVM平台设计。Groovy闭包作为其核心特性之一,提供了比Java Lambda表达式更灵活、更强大的编程能力。本文将深入探讨Groovy闭包编程的完整指南,揭示其超越Java Lambda的独特优势。 ## 📌 Groovy闭包基础:从入门到精通 Groovy闭包是一个开放的、匿名的代码块,可以接受参数、返回值,并分配给变量。

gitblog_00692的博客 486

Go接口本质:隐式契约、最小原则与 nil 陷阱解析

Go接口并非传统面向对象中的抽象类,而是一种编译期静态检查的隐式能力契约,其核心是‘能做什么’而非‘是什么’。它基于鸭子类型思想,通过方法签名完全匹配实现自动满足,支撑了io.Reader等最小接口的广泛复用。这种设计带来高度解耦与组合自由,但也引入nil判断陷阱、类型断言安全性和接口演化约束等工程挑战。理解接口的动态类型/值二元性、消费端定义原则及与泛型的协同边界,是构建可测、可维护Go服务的关键技术基础。

weixin_30564901的博客 742
上一篇: Project Euler解题汇总 051 ~ 060
下一篇: Java.next:第一部分——共同点
JavaSxy
博客等级 码龄21年 1粉丝 25原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址