gpt4 book ai didi

haskell - Swift 中的函数式思维?

转载 作者:搜寻专家 更新时间:2023-11-01 05:59:12 25 4
gpt4 key购买 nike

我开始学习 Haskell 和 Swift。我想知道这是否是以“功能”方式思考的正确方式?问题是创建卡片组:我需要遍历花色和等级——为每个花色创建具有给定花色和等级的卡片。以“命令式”的方式是:

let suits: Array<Character> = ...
let ranks: Array<Int> = ...

var cards: [Card]
for suit in suits {
for rank in ranks {
cards.addObject(Card(suit: suit, rank: rank))
}
}

然后我尝试使用递归的纯函数,它可以工作但是,可以用更少的代码来完成吗?对我来说,Swift 中的“函数式”可读性较差,或者我可能做错了......

let cards = cardsWithSuits(suits, ranks, [Card]());

func cardsWithSuits(suits: [Character], ranks: [Int], cards: [Card]) -> [Card] {
if suits.count == 0 { return cards }
let suit: Character = head(suits)!
let acc = cardsWithRanks(ranks, suit, cards)

return cardsWithSuits(drop(1, suits), ranks, acc)
}

func cardsWithRanks(ranks: [Int], suit: Character, cards: [Card]) -> [Card] {
if ranks.count == 0 { return cards }
let acc = cards + [Card(suit: suit, rank: head(ranks)!)]

return cardsWithRanks(drop(1, ranks), suit, acc)
}

最佳答案

基于 Haskell 的应用概念和 <$> 的使用和 <*>您可能会发现以下内容通常很有用(我认为我的翻译是正确的,尽管它是基于数组而不是序列):

// use <^> because <$> is already used
infix operator <^> { associativity left }
public func <^> <T, U>(left:(T)->U, right:[T]) -> [U] {
return map(right) { return left($0) }
}

public func flatten<T>(input:[[T]]) -> [T] {
return input.reduce([], +)
}

infix operator <*> { associativity left }
public func <*> <T, U>(left:[(T)->U], right:[T]) -> [U] {
return flatten(map(left) { (function) -> [U] in
return map(right) { return function($0) }
})
}

然后允许您使用以下内容:

let suits : [Character] = [ "C", "D", "H", "S"]
let ranks = Array(2...14)

struct Card {
let suit : Character
let rank : Int

static func build(suit:Character)(rank:Int) -> Card {
return Card(suit: suit, rank:rank)
}
}

Card.build <^> suits <*> ranks

关于haskell - Swift 中的函数式思维?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27808198/

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