是否有一个现有的模式来为两个列表中的每个项目组合生成一个函数的应用程序列表? [英] Is there an existing pattern to generate a list of the applications of a function to every combination of the items in two lists?

查看:98
本文介绍了是否有一个现有的模式来为两个列表中的每个项目组合生成一个函数的应用程序列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进入函数式编程,并且正在尝试一些不重要的示例并询问其他人是否做错了阶段。我遵循Don Syme的

I'm just getting into functional programming and i'm in the "try out some non-trivial examples and ask others if I'm doing it wrong" phase. I'm following Don Syme's F# Tutorial and have decided to take a stab at the blackjack exercise at the end of Part II with a twist: he suggests treating Ace as 11 for simplicity's sake, but I decided to ignore that recommendation.

我处理它的方式是给每个卡片等级一个可能的值列表,并递归地建立一个可能的手牌值列表:

The way I'm handling it is by giving each card rank a list of possible values and building up a list of possible hand values recursively thus:

let cardValues (Card(rank, _)) =
    match rank with
    | Ace                 -> [1; 11]
    | King | Queen | Jack -> [10]
    | Value(value)        -> [value]

let rec handValues = function
    | [] -> [0]
    | card::cards ->
        [
            for handValue in handValues cards do
                for cardValue in cardValues card do
                    yield handValue + cardValue
        ]

handValues 函数在结构上非常类似于fold,所以我无法摆脱那里的感觉已经有一些高级功能可以用来完成这个功能。有什么我失踪或者这是非常正确的方向?

The handValues function is so similar in structure to a fold that I can't shake the feeling there's already some high order function I can use to accomplish this. Is there something I'm missing or is this pretty much the right direction?

推荐答案

值得一提的是, / p>

It's worth mentioning as an aside that this

    [ 
        for handValue in handValues cards do 
            for cardValue in cardValues card do 
                yield handValue + cardValue 
    ] 

是一个monadic绑定;可以编写一个'list'monad,然后使用计算表达式将其写为

is a monadic bind; one could author a 'list' monad and then use computation expressions to write this as

listMonad {
    let! handVal = handValues cards
    let! cardVal = cardValues card
    return hardVal + cardVal
}

这篇关于是否有一个现有的模式来为两个列表中的每个项目组合生成一个函数的应用程序列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆