为什么我感觉我的F#代码可能更简洁

时间:2016-01-07 14:40:55

标签: f# immutability

我是一名经验丰富的C#开发人员,他试图自学F#。我花了一天或三天的时间阅读F# wikibook试图了解语法和F#基础知识。

作为练习,我正在尝试解决Project Euler问题,以更好地理解语法并使用该语言。

我刚刚解决了problem 5。但是我不太高兴我必须跳过这个箍来获得代表我的解决方案的数据结构。 我已经使用this blogpost来找到解决问题的算法。

我想知道是否有人可以给我一些关于如何改进此代码的指示?我的猜测是,F#值固有的不变性导致我必须执行大量步骤才能获得我想要的确切数据...

这是我的代码:

sqlconn = New MySqlConnection
sqlconn.ConnectionString = "server=localhost;userid=root;password='';database=innovative"
Try
    sqlconn.Open()
    query = "SELECT Full_Name FROM employee WHERE ID='" & txt_id_number.Text & "'"
    cmd = New MySqlCommand(query, sqlconn)
    reader = cmd.ExecuteReader
    If reader.HasRows = False Then
        MsgBox("Invalid ID number please secure that the  ID number is already Exist" & vbNewLine & "TAKE NOTE:" & vbNewLine & "You cannot update or change the existing ID number for it is the primary Key for the Employee, If you want to Change it, its better to delete the Employee then add it again." & vbNewLine & "Other than that you can change the Full name, age, contact and etc.", vbCritical)

    Else
        reader.Close()
        sqlconn.Open()
        query1 = "UPDATE employee SET Full_Name ='" & txt_fullname.Text & "', Employee_Type='" & txt_employee_type.Text & "', Age='" & txt_age.Text & "',Sex='" & cb_sex.Text & "', Status='" & txt_status.Text & "', Contact ='" & txt_contact.Text & "',E_mail='" & txt_email.Text & "' WHERE ID = '" & txt_id_number.Text & "'"
        cmd = New MySqlCommand(query1, sqlconn)
        reader1 = cmd.ExecuteReader
        MsgBox(txt_fullname.Text & " was successfully updated", vbInformation)
        txt_age.Text = ""
        txt_contact.Text = ""
        txt_email.Text = ""
        txt_employee_type.Text = ""
        txt_fullname.Text = ""
        txt_id_number.Text = ""
        txt_status.Text = ""
        cb_sex.Text = ""
        add_employee()
    End If
    sqlconn.Close()
Catch ex As Exception
Finally
    sqlconn.Dispose()
End Try

1 个答案:

答案 0 :(得分:5)

您可以对代码应用许多直接简化,但我认为这不是最好的方法。

这就是我在F#中解决这个问题的方法:

let rec tryDivide n m =
    if m = 1 then true
    else
        if n % m = 0 then tryDivide n (m-1)
        else false

let rec findIt i m =
    if tryDivide i m then i
    else findIt (i+1) m

findIt 1 20

它比你的慢一点,因为它不使用硬编码的素数,它们是在运行中计算的,但是我的计算机上仍需要不到2秒的时间才能得到正确的答案。

请注意,我没有使用任何类似列表的数据结构,也不需要在这个特定问题上依赖大整数。

<强>更新

这是基于Kvb提出的解决方案的更好方法:

let rec gcd x y = if y = 0 then abs x else gcd y (x % y)

let lcm a b = 
    match (a, b) with
    | (_, 0) | (0, _) ->  0
    | (x, y) -> abs ((x / (gcd x y)) * y)

Seq.fold lcm 1 {2..20}