编程技术网

 用户名 Email 自动登录 找回密码 密码 立即注册

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

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

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

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

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

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
| _ -> [] //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)

^