我有一个整数序列,表示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) diceremoves 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 listEDIT: 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 listHowever 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#中的序列中删除单个非唯一值
发布评论