[英]How can I repeat calling a function until it returns None?
Suppose I have 2 functions 假设我有2个功能
Func<Id, Option<Employee>> FindEmployee
It returns an employee if the Id is found, otherwise None
; 如果找到该ID,它将返回一个雇员,否则返回
None
;
Func<Employee, Option<Entry>> PromptPassword
It will open a dialog asking for password, if OK button is hit, it will return the user entry; 它将打开一个对话框,要求输入密码,如果单击确定按钮,将返回用户输入。 if cancel is hit, it will return None
如果取消被击中,它将返回无
I would like to have an elegant way to composite these 2 functions, basically I want to do: 我想以一种优雅的方式来组合这两个函数,基本上我想这样做:
FindEmployee.Map(emp =>
{
while (true)
{
var result = PromptPassword (emp);
if (result.IsNone)
{
return false;
}
bool matched = result.Where(a => a.EntryContent == emp.Password)
.Some(r => true)
.None(false);
if (matched)
return true;
}
});
The end result is an Option You see, I want to keep prompting for password until the user enter it correctly. 最终结果是一个选项,您看到的是,我想不断提示输入密码,直到用户正确输入为止。 But using a while loop inside a
Map
is so ugly. 但是在
Map
使用while循环是如此丑陋。
It must have a better way to write this. 它必须有更好的方式来编写此代码。 can anyone give a hint?
有人可以给个提示吗?
Thanks 谢谢
define a function like this 定义这样的功能
bool Insist(Employee:emp){
var result = PromptPassword (emp);
if (result.IsNone)
{
return false;
}
bool matched = result.Where(a => a.EntryContent == emp.Password)
.Some(r => true)
.None(false);
if(matched)
{
return true;
}else
{
return Insist(emp);
}
}
Then you can just go and 那你就可以去
FindEmployee(id).Map(emp =>
{
return Insist(emp);
});
In F# I would probably express your algorithm like this: 在F#中,我可能会这样表达您的算法:
findEmployee |> Option.map (fun emp ->
let rec loop () =
match PromptPassword emp with
| None -> false
| Some a -> a.EntryContent = emp.Password || loop ()
loop ())
The equivalent in C# would probably look as follows: C#中的等效项可能如下所示:
FindEmployee.Map(emp =>
{
do {
var result = PromptPassword(emp);
if (result.IsNone) return false;
} while (result.Where(a => a.EntryContent == emp.Password).IsNone);
return true;
});
You could make use of the goto statement right? 您可以使用goto语句对吗? and then get rid of the while loop...
然后摆脱while循环...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.