我开始学习Haskell和Swift。我想知道它是否是正确的思维方式" functional"办法? 问题是创建卡片组: 我需要循环穿西装和排名 - 为每件西装创造出具有特定西装和等级的卡片。在"命令式"它的方式是:
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))
}
}
然后我尝试使用递归的纯函数,它可以工作但是,可以用更少的代码完成吗? 对我来说&#34;功能性&#34;在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)
}
答案 0 :(得分:5)
在使用Haskell的应用概念以及<$>
和<*>
的基础上,您可能会发现以下内容通常很有用(我认为我已经正确翻译了,尽管它已经&#39; s基于数组而不是序列):
// 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
答案 1 :(得分:1)
这可能不太漂亮,我不认为它是函数式编程,但它代码较少,它使用了Swift的极好的映射并减少了函数:
struct Card {
let suit: String
let rank: Int
}
let cards = ["Heart", "Diamond", "Club", "Spade"].reduce([Card]()) { (cards, suit) in
return cards + map(1...13) { rank in return Card(suit: suit, rank: rank) }
}
答案 2 :(得分:0)
Swift不是一种功能语言。但是,您可以在函数式中编写快速代码。
func map<T: Collection, U>( _ transform: (T.Iterator.Element) -> U, _ xs: T) -> [U] {
return xs.reduce([U](), {$0 + [transform($1)]})
}
func concatMap<A, B> (_ process: (A)->[B], _ xs: [A]) -> [B] {
return xs.reduce([B](), {$0 + process($1)})
}
infix operator <*>
func <*><A, B>(_ xs: [A], _ ys: [B]) -> [(A, B)]{
let transform: (A, B) -> (A, B) = {($0, $1)}
return concatMap({x in map({transform(x, $0)}, ys)}, xs)
}
struct Card {
let suit : Character
let rank : Int
static func build(_ sr: (s:Character, r:Int)) -> Card {
return Card(suit: sr.0, rank: sr.1)
}
}
func test() {
let suits : [Character] = [ "C", "D", "H", "S"]
let ranks = Array(1...13)
let cards = map(Card.build, suits <*> ranks)
print(cards)
}
如果您想学习Haskell和Swift,可以参考https://github.com/unchartedworks/HaskellSwift