编程技术网

关注微信公众号,定时推送前沿、专业、深度的编程技术资料。

 找回密码
 立即注册

QQ登录

只需一步,快速开始

极客时间

从F#中的序列中删除单个非唯一值:Remove a single non-unique value from a sequence in F#

Kaji Islam 序列 2022-5-11 19:30 6人围观

腾讯云服务器
从F#中的序列中删除单个非唯一值的处理方法

我有一个整数序列,表示F#中的骰子.

在上述游戏中,玩家有一个骰子池,可以选择玩一个骰子(由某些规则管理)并保留其余骰子.

例如,如果玩家掷出6、6和4并决定玩6,则有没有简单的方法来返回只删除6的序列?

  Seq.filter(fun x-> x!= 6)骰子 

删除所有六个数字,而不仅仅是一个.

解决方案

下面的代码将适用于列表(因此,没有任何序列,但听起来您使用的序列可能是列表)

  let rec removeOne值列表=符合清单|head :: tail,当head =值->尾巴|head :: tail->头::(删除一个值尾)|_->[]//您可能想在这里失败,因为它没有发现价值//列表 

基于下面的正确注释更新了代码.谢谢P

在阅读了不同的答案之后,我认为应该有一个警告.不要将以上代码用于无限期序列,但由于我猜您的玩家没有无限期骰子,这应该不是问题,但为了完整起见,这是一个适用于(几乎)任何情况的实现有限序列

 让rec removeOne值seq acc =匹配seq.Any()与|当s.First()= value->时为true.顺序跳过(1)|正确->seq.First():: :(删除一个值seq.Skip(1))|_->List.rev acc//您可能想要在这里失败,因为它没有在//列表 

但是,我建议您使用第一种解决方案,即使您必须先将序列转换为列表(至少对于小序列或最后具有寻求值的大序列),Im充满信心的解决方案也要比后者好 >

I have a sequence of integers representing dice in F#.

In the game in question, the player has a pool of dice and can choose to play one (governed by certain rules) and keep the rest.

If, for example, a player rolls a 6, 6 and a 4 and decides to play one the sixes, is there a simple way to return a sequence with only one 6 removed?

Seq.filter (fun x -> x != 6) dice

removes all of the sixes, not just one.

解决方案

the below code will work for a list (so not any seq but it sounds like the sequence your using could be a List)

let rec removeOne value list = 
               match list with
               | head::tail when head = value -> tail
               | head::tail -> head::(removeOne value tail)
               | _ -> [] //you might wanna fail here since it didn't find value in
                                   //the list

EDIT: code updated based on correct comment below. Thanks P

EDIT: After reading a different answer I thought that a warning would be in order. Don't use the above code for infite sequences but since I guess your players don't have infite dice that should not be a problem but for but for completeness here's an implementation that would work for (almost) any finite sequence

 let rec removeOne value seq acc = 
                   match seq.Any() with
                   | true when s.First() = value -> seq.Skip(1)
                   | true -> seq.First()::(removeOne value seq.Skip(1))
                   | _ -> List.rev acc //you might wanna fail here since it didn't find value in
                                       //the list

However I recommend using the first solution which Im confident will perform better than the latter even if you have to turn a sequence into a list first (at least for small sequences or large sequences with the soughtfor value in the end)

这篇关于从F#中的序列中删除单个非唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程技术网(www.editcode.net)!

腾讯云服务器 阿里云服务器
关注微信
^