gpt4 book ai didi

scala - Scala中的函数式编程示例

转载 作者:行者123 更新时间:2023-12-04 10:11:26 24 4
gpt4 key购买 nike

我正在学习scala。非常感谢Odersky和其他所有作者的出色工作。

我提出了一个欧拉问题(http://projecteuler.net/),以提供一个更多然后最小的示例。我正在尝试采用功能性方式。因此,这不是“请立即回答我,否则我的老板会杀了我”,而是“请,如果您有时间,您可以帮助命令式语言程序员踏上函数世界吗?”

问题:我想要一门关于扑克手的类(class)。扑克之手是由从0到5的许多纸牌组成的。我想一劳永逸地建立纸牌列表,即:我的手类将是不可变的,如果我想添加一张纸牌,则我创建一个新的Hand对象。
因此,我需要一个可以创建为“val”而不是var的Card集合。
第一步:构造函数,每张卡片一张。但是Card的集合是在每个构造函数中处理的,因此我必须将其作为var!

这是代码,Card类只是一个Suit和一个Value,作为字符串传递给构造函数(“5S”是黑桃5):

class Hand(mycards : List[Card]) {
// this should be val, I guess
private var cards : List[Card] = {
if (mycards.length>5)
throw new IllegalArgumentException(
"Illegal number of cards: " + mycards.length);
sortCards(mycards)
}

// full hand constructor
def this(a : String, b : String, c : String, d : String, e : String) = {
this(Nil)

// assign cards
val cardBuffer = new ListBuffer[Card]()
if ( a!=null ) cardBuffer += new Card(a)
if ( b!=null ) cardBuffer += new Card(b)
if ( c!=null ) cardBuffer += new Card(c)
if ( d!=null ) cardBuffer += new Card(d)
if ( e!=null ) cardBuffer += new Card(e)
cards = sortCards(cardBuffer.toList)
}
// hand with less then 5 cards
def this(a : String, b : String, c : String, d : String) = this(a,b,c,d,null)
def this(a : String, b : String, c : String) = this(a, b, c, null)
def this(a : String, b : String) = this(a, b, null)
def this(a : String) = this(a, null)
def this() = this(Nil)

/* removed */
}

您知道如何使其成为真正的功能方式吗?
谢谢。

PS:如果您真的想知道,那就是问题54。

最佳答案

我的答案与scala的功能无关,但是您可以使用scala sugar很快编写代码:

class Hand(val mycards: List[Card]) {
require (mycards.size <= 5,"can't be more than five cards")
def this(input: String*) = {
this(input.map(c => new Card(c)).toList)
}
}

辅助构造函数中的 input: String*表示您可以具有可变数量的参数(成千上万个字符串)。
我正在使用 map函数获取输入并为每个新Card调用创建,然后将结果传递给具有自己的 需求的父构造函数。
(顺便说一句,从字符串到Card的映射可以以这种方式匿名完成: this(input.map(new Card(_)).toList))
class Hand(val mycards: List[Card]) {...
等于
class Hand(cards: List[Card]) {
val mycards = cards
...

从现在开始,如果您尝试创建超过5张卡片,您将获得 java.lang.IllegalArgumentException:
scala> class Card(s: String) {println("Im a :"+s)}
defined class Card

scala> new Hand("one","two","three","four","five","six")
Im a :one
Im a :two
Im a :three
Im a :four
Im a :five
Im a :six
java.lang.IllegalArgumentException: requirement failed: can't be more than five card
at scala.Predef$.require(Predef.scala:157)
at Hand.<init>(<console>:9)

关于scala - Scala中的函数式编程示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7007805/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com