从F#中的序列中删除单个非唯一值

编程入门 行业动态 更新时间:2024-10-28 06:32:47
本文介绍了从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#中的序列中删除单个非唯一值

本文发布于:2023-10-23 04:27:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519786.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列   非唯一值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!