我该如何用F#或其他函数语言来写呢
我知道在F#中,赋值时会声明变量。我相信你可以用C语言声明变量,但是我该怎么写呢我该如何用F#或其他函数语言来写呢,f#,F#,我知道在F#中,赋值时会声明变量。我相信你可以用C语言声明变量,但是我该怎么写呢 long id=0 using (SQLiteDataReader r = command.ExecuteReader()) { while (r.Read()) { id = r.GetInt64(0); //... break; } } //use id in sqlite now that it isnt locked 理想情况下,您应
long id=0
using (SQLiteDataReader r = command.ExecuteReader())
{
while (r.Read())
{
id = r.GetInt64(0);
//...
break;
}
}
//use id in sqlite now that it isnt locked
理想情况下,您应该编写一个单独的函数并从该函数返回值。所以在C#中: 粗略翻译:
let mutable id = 0L
(
use r = command.ExecuteReader()
let mutable finished = false
while not(finished) do
if r.Read() then
id <- r.GetInt64(0)
// ...
finished <- true
else
finished <- true
)
// ...
让可变id=0L
(
使用r=command.ExecuteReader()
设mutable finished=false
虽然没有(完成)做
如果r.Read()那么
id首先,我不确定您的示例中是否需要任何循环。您的代码总是从第一行返回值。我将使示例稍微复杂一点,并假设您可能不希望得到某些id作为结果(因此您可能需要执行一些循环)
在函数语言中编写循环构造的常用方法是使用递归(在许多情况下,可以避免显式使用递归,因为有许多有用的高阶函数可以直接使用)。在这种情况下,可以编写一个简单的递归函数read
,调用r.read()
一次-如果成功,则返回ID;如果失败,则递归调用自身以读取下一行:
let id =
( use r = command.ExecuteReader()
let rec read() =
if r.Read() then
let id = r.GetInt64(0)
if weWantThisId id then id // this is the ID we want
else read() // continue reading IDs
else 0 // default value / throw
read() )
read
函数在初始化id
值的作用域中作为本地函数写入。这意味着当F#将值赋给id
时,它将运行ExecuteReader
,然后运行本地函数read
(这是将初始化作为单个表达式写入的一种方式)当然,按照Jon的建议编写fetchId
函数可能更具可读性(在F#中,您将再次使用递归):
在r
上调用Dispose如何?第二个代码段中缺少一行,因此这可能会造成混乱。无论如何,我使用的是use
,因此r
在超出范围时(在第一个示例中计算ID后或在第二个示例中从函数返回后)将自动处理.perfect,第一个例子回答了我的问题。实际上,我的代码有一个循环和中断的原因是bc,在那里有一个if(cond)continue和cond语句(在它自己的函数中没有意义)。我喜欢在有自己作用域的if语句中分配变量的能力。使用实际的可变变量(并非在所有函数式语言中都有,但在F#中有),我想这是对所问问题最准确的回答。
let id =
( use r = command.ExecuteReader()
let rec read() =
if r.Read() then
let id = r.GetInt64(0)
if weWantThisId id then id // this is the ID we want
else read() // continue reading IDs
else 0 // default value / throw
read() )
let fetchId() =
use r = command.ExecuteReader()
let rec read() =
if r.Read() then
let id = r.GetInt64(0)
if weWantThisId id then id
else read()
else 0
read()