如果让莎士比亚海明威编写JavaScript代码.docx

上传人:b****6 文档编号:7577709 上传时间:2023-01-25 格式:DOCX 页数:9 大小:21.44KB
下载 相关 举报
如果让莎士比亚海明威编写JavaScript代码.docx_第1页
第1页 / 共9页
如果让莎士比亚海明威编写JavaScript代码.docx_第2页
第2页 / 共9页
如果让莎士比亚海明威编写JavaScript代码.docx_第3页
第3页 / 共9页
如果让莎士比亚海明威编写JavaScript代码.docx_第4页
第4页 / 共9页
如果让莎士比亚海明威编写JavaScript代码.docx_第5页
第5页 / 共9页
点击查看更多>>
下载资源
资源描述

如果让莎士比亚海明威编写JavaScript代码.docx

《如果让莎士比亚海明威编写JavaScript代码.docx》由会员分享,可在线阅读,更多相关《如果让莎士比亚海明威编写JavaScript代码.docx(9页珍藏版)》请在冰豆网上搜索。

如果让莎士比亚海明威编写JavaScript代码.docx

如果让莎士比亚海明威编写JavaScript代码

如果让莎士比亚、海明威编写JavaScript代码

最近,我做了一个梦,我请海明威和其他四位文学名人替我编写JavaScript代码,一个函数返回一个给定长度的斐波纳契数列。

有趣地是,他们每个人都以不同的方式完成了这一题,并且都做的很好——只是我想说,每个解决方案工作起来都好比广告(即使是AndreBreton的),后来我又请包括海明威在内的7名文豪用JavaScript来编写阶乘,似乎一切都那么神奇,但他们都成功地完成了,大家不妨来看看结果吧。

  一、实现斐波纳契数列

  1.欧内斯特·海明威(ErnestHemingway美国作家)

  代表作:

《老人与海》《太阳照样升起》《永别了,武器》《丧钟为谁而鸣》

functionfibonacci(size){

varfirst=0,second=1,next,count=2,result=[first,second];

if(size<2)

return"therequestwasmadebutitwasnotgood"while(count++

next=first+second;

first=second;

second=next;

result.push(next);

}

returnresult;

}

  简洁明了的代码,没有任何多余的字母和变量,没有精心设计的逻辑和聪明的变量命名,非常平淡地表明了它是做什么的,仅此而已,这就是海明威的魅力之处。

  2.威廉·莎士比亚(WilliamShakespeare英国诗人、戏剧家)

  代表作:

《哈姆雷特》《奥赛罗》《李尔王》《罗密欧与朱丽叶》等

functiontheSeriesOfFIBONACCI(theSize){

//aCALCKULATIONintwoacts.//employ'ngthehumourouslogickofJAVA-SCRIPTE//DramatisPersonaevartheResult;

//anARRAYtocontainTHENUMBERSvartheCounter;

//aNUMBER,serv'nttotheFORLOOP//ACTI:

inwhichaZEROisaddedforINITIATION//[ENTER:

theResult]//UponthenoblelistbestowazerovartheResult=[0];

//ACTII:

aLOOPinwhichthefinalTWONUMBERSareQUEREEDandSUMM'D//[ENTER:

theCounter]//Commenceatoneandventureo'erthenumbersfor(theCounter=1;theCounter

//BydivinationsetadjoiningmemberstheResult[theCounter]=(theResult[theCounter-1]||1)+theResult[Math.max(0,theCounter-2)];

}

//'Tisdone,andhere'stheanswer.returntheResult;

//[Exuent]}

  大家可以看看莎士比亚是如何使用抑扬格五音步编写注释的。

熟悉他戏剧的朋友应该对抑扬格五音步非常熟悉吧。

  3.安德烈·布勒东(AndreBreton法国诗人)

  代表作:

《超现实主义宣言》

functionColette(umbrella){

varstaircase=0,galleons=0,brigantines=1,armada=[galleons,brigantines],bassoon;

Array.prototype.embrace=[].push;

while(2+staircase++

bassoon=galleons+brigantines;

armada.embrace(brigantines=(galleons=brigantines,bassoon));

}

returnarmada;

}

  整个解决方案的逻辑非常清晰、优雅,在galleons、brigantines、bassoons这三个之间,使用逗号操作符对它们进行同时转移。

  4.罗贝托·波拉尼奥(RobertoBolano智利小说家、诗人)

  代表作:

《荒野侦探》《2666》

functionLeonardoPisanoBigollo(l){

if(l<0){

return"I'dprefernottorespond.(Althoughseveralrepliesoccurtome)"}

/**///Everythingisgettingcomplicated.for(vari=2,r=[0,1].slice(0,l);i

/**///Herearesomeothermathematicians.Mostlyit'sjustnonsense.rationalTheorists=["ArchimedesofSyracuse","PierredeFermat(suchmargins,boys!

)","SrinivasaRamanujan","ReneDescartes","LeonhardEuler","CarlGauss","JohannBernoulli","JacobBernoulli","Aryabhata","Brahmagupta","BhaskaraII","NilakanthaSomayaji","OmarKhayyám","MuhammadibnMūsāal-Khwārizmī","BernhardRiemann","GottfriedLeibniz","AndreyKolmogorov","EuclidofAlexandria","JulesHenriPoincaré","SrinivasaRamanujan","AlexanderGrothendieck(whocouldforget?

)","DavidHilbert","AlanTuring","vonNeumann","KurtGödel","Joseph-LouisLagrange","GeorgCantor","WilliamRowanHamilton","CarlJacobi","ÉvaristeGalois","NikolayLobachevsky","ReneDescartes","JosephFourier","Pierre-SimonLaplace","AlonzoChurch","NikolayBogolyubov"]

/**///Ididn'tunderstandanyofthis,buthereitisanyway.returnr

/**///NothinghappenshereandifitdoesI'drathernottalkaboutit.}

  长短不齐的段落,缺少分号,使用隐式全局变量——对每一个变量都做进一步深入的说明。

  5.查尔斯·狄更斯(CharlesDickens英国小说家)

  代表作:

《匹克威克外传》《雾都孤儿》《双城记》等

functionmrFibbowicksNumbers(enormity){

varassortment=[0,1,1],tally=3,artfulRatio=1.61803;

while(tally++

//hereisanexceedinglycleverdeviceassortment.push(Math.round(assortment[tally-2]*artfulRatio));

}

//shouldtherebeanoverabundanceofelements,aremedyneedbeappliedreturnassortment.slice(0,enormity);

}

  从代码中可以看出,他没有体会到斐波那契数列的基本理念,而是采用乘法解决。

代码里也有些有趣的命名,但缺乏核心地理解。

  二、实现factorial(n)阶乘

以上是这些著名的作家用JavaScript编写斐波那契数列,下面再让我们看看,作家们是如何用JavaScript/CoffeeScript编写factorial(n)的。

  1.杰克·凯鲁亚克(JackKerouac美国小说家)

  代表作:

《在路上》《贩毒者》等

/*...theonlynumbersformearethemadones,takeforty-threelikea

steamenginewithatalkycabooseattheend*/n=43,

/*andthatlanky

fellowinacockedfedora*/r=1/*thenbacktoournumber,ourmad

number,madtobecomeone*/while(n>1)

/*madtodescend*/n--,

/*mad

tomultiply*/r=r*n

/*andattheend,youseethebluecenter-light

pop,andeverybodygoes1.4050061177528801e+51...*/r

  上面代码只能返回43的阶乘,如果想要实现另一个数的阶乘,你还需重写代码。

不过,最值得注意地是,注释和代码几乎没有区别,无法分辨,从侧面反映了Kerouac的风格,很长、狂野和狂想式的流露。

  2.塞缪尔·约翰逊(SamuelJohnson英国作家、诗人)

  代表作:

《英语大辞典》《伦敦》《人类欲望的虚幻》等

#InwhichvariousNUMBERSaresummon'dby

#meansofELECTRONICKCONJURY

factorial=(n)->

#Allargumentisagainstit;yetallbeliefisforit

return1unlessn

#Ingenioussophistrytoprovethepalp'blyOBVIOUS

return1ifnis1#Recursion(n.)

#aprogramthatcalls'ponitselfinthemannerof

#adogreturninguntoitsVOMIT

returnn*factorialn-1

  整段代码比较稀疏,中间也掺杂着Johnson的精言妙语:

其中,他也对factorial(0)应该为1进行了怀疑,他应该用一个完整的句子来表达factorial

(1)就是1,从其字典里进行推测,完成了一个具有讽刺定义的递归解除。

  Johnson的整个解决方案充满着艺术和模仿的结合——带有整洁表达式地温和的自我嘲讽和真正美丽的混合。

  3.詹姆斯·乔伊斯(JamesJoyce爱尔兰作家、诗人)

  代表作:

《尤利西斯》

functionhacktorial(integette){

varnonthings=[undefined,null,false,0,'',NaN];

varresultution=1;

if(integette==0){

//beholdthestrangerouszeroine!

resultution=1;

}else{

while(integette>1)

//caligulatebymulticapablesresultution=resultution*integette--;

}

with(resultution){

varduodismal=Function('returnthis').call(toString(12));

vardisemvowel=Function("n","returnn?

parseInt(n,12):

'0'")

return[

disemvowel(duodismal.slice(0,-1)),

'shillingsand',

disemvowel(duodismal[duodismal.length-1]),'pence'].join('');

}

//klikkaklakkaklaskaklopatzklatschabattacreppycrottygraddahappluddyappladdypkonpkot!

}

  Joyce不仅仅是解决了阶乘问题,前半部分代码已经解决了这个问题,但Joyce坚决把结果转换为当时的货币:

先令和便士。

  结果:

hacktorial(3)

//"0shillingsand6pence"hacktorial(4)

//"2shillingsand0pence"hacktorial(7)

//"420shillingsand0pence"hacktorial(21)

//"4257578514309120000shillingsand0pence"

  4.理查德·费曼(RichardFeynman美国物理学家)

  代表作:

《费曼物理学讲义》《物理之美》

//usingRamanujan'sapproximationfunctionfractorail(n){

with(Math){

varr=sqrt(PI)*pow(n/E,n);r*=pow(8*pow(n,3)+4*(n*n)+n+1/30,1/6);

returnr;

}

}

  费曼的工作的特点是具有大胆的创意和非常古怪的才华,从它所编写的这段代码中也能看出。

  结果,不要担心一些“舍入误差”,如果你非常熟悉JavaScript,你就应该知道:

fractorail(3);

//6.00005fractorail(1.1);

//1.04671fractorail(5.2);

//169.40628

  5.阿瑟·柯南·道尔(ArthurConanDoyle世界著名小说家)

  代表作:

《福尔摩斯探案集》《失落的世界》

"usestrict";

//Insolvingaproblemofthissort,thegrandthingistobeabletoreasonbackwards...//somethingsareeasierknownthanexplained!

varcaseHistory=newObject({2:

2,6:

3});

functionunfactorial(evidence){

//first,humility!

if(evidence===1){

return"Watson,Iamataloss!

"}

//second,logicalprecedence!

if(caseHistory[evidence]){

//elementary!

returncaseHistory[evidence];

}

//third,eliminatetheimpossible!

if(evidence===0||evidence%24!

==0){

return"charlatans!

";

}

//fourth,deduction!

vartheDeduction,enumarator=evidence,denominator=1;

while(enumarator%denominator===0){

enumarator=enumarator/denominator++;if(enumarator===denominator){

theDeduction=enumarator;

}

}

theDeduction=theDeduction||"impostors";

//Whatonemancaninventanothercandiscover!

caseHistory[evidence]=theDeduction;

//Whatremains,howeverimprobable,mustbethetruth!

returntheDeduction;

}

  正如大家想象的那样,柯南道尔的设计过程是精确和认真有序的,此外,大家可能注意到,他让其应用程序在strict模式运行——容不得半点马虎。

  6.简·奥斯汀(JaneAusten英国小说家)

  代表作:

《理智与情感》《傲慢与偏见》

factorial=(function(){

//Ideclare...varledger={};

returnfunctionreckoning(quantity){

if(isNaN(quantity)){

console.log("Ihavenotthepleasureofunderstandingyou");

return;

}

//Itisatruthuniversallyacknowledgedthattwovalues//canonlybeadjudgedtrulyagreeablebymeansof===if(quantity===0){

return1;

}

//MrCrockfordteachesthatwebewaryofinheritedproperty...if(ledger.hasOwnProperty(quantity)){

returnledger[quantity];

}

//Praypersistuntilananswerisfurnishedreturnledger[quantity]=quantity*reckoning(quantity-1);

};

})();

  JaneAusten解决方案的亮点之一是代码工艺和结构的完整性,主要体现在代码块的整洁上,她调用模块模式,隐藏历史数据(或ledger)在上层结构的文件夹里;第二个则是体现了JaneAusten的俏皮,甚至是颠覆性的,对power的讽刺和荒谬的约定。

  7.欧内斯特·海明威(ErnestHemingway美国小说家)

  代表作:

《老人与海》《太阳照样升起》等

//Economy.functionfactorial(n){

returnn<2?

1:

factorial(n-1)*n;

}

  代码足以说明一切。

  我们从中所学到的

  这些著名的小说家、诗人、戏剧家的伟大之处在于他们勇于开拓新方式,尝试新的技术并且打破我们一直所遵循的规律。

最优秀的英语作家具有着对规则的蔑视。

——StevenPinker

  JavaScript作为最流行的编程语言之一,它的进步取决于开发者们地大胆创新、研究以及发现新模式,这样才能惠及更多的人。

 

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 经管营销 > 经济市场

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1