将C#代码转换为F#(如果声明) [英] Converting C# code to F# (if statement)

查看:92
本文介绍了将C#代码转换为F#(如果声明)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何逐行将此代码从C#转换为F#。我不想使用任何F#的惯用法或类似用法。我试图了解如何直接映射 C#的结构到F#。

I'd like to know how to convert this code line by line from C# to F#. I am not looking to use any kind of F#'s idioms or something of the like. I am trying to understand how to map directly C#'s constructs to F#.

这是C#代码:

//requires l.Length > 0
int GetMinimumValue(List<int> l) {
    int minVal = l[0];

    for (int i = 0; i < l.Length; ++i) {
        if (l[i] > minValue) {
            minVal = l[i];
        }
    }

    return minVal;
}

这是我的F#尝试:

let getMinValue (l : int list) =
    let minVal = l.Head

    for i = 0 to (l.Length-1) do
        if (l.Item(i) > minVal) then
            minVal = col.Item(i)

    minVal

现在,这不起作用。问题似乎与 minVal = col.Item(i)行有关:

Now, this ain't working. The problem seems to be related with the minVal = col.Item(i) line:

This expression was expected to have type     unit     but here has type     bool

什么是

推荐答案

如果要逐行转换,请尝试以下操作

If you want to convert it line by line then try the following

let getMinValue (l:System.Collections.Generic.List<int>) =
  let mutable min = l.Item(0)
  for i = 0 to (l.Count-1) do
    if l.Item(i) < min then min <- l.Item(i)
  min

现在为什么您会收到该特定错误。看看下面的行

Now as to why you're getting that particular error. Take a look at the following line

minVal = col.Item(i)

在F#中,这不是分配而是比较。因此,这是一个产生布尔值的表达式,但是在 for 循环内,所有表达式必须为 void / unit 返回。因此,您会收到一个错误。

In F# this is not an assignment but a comparison. So this is an expression which produces a bool value but inside the for loop all expressions must be void/unit returning. Hence you receive an error.

在F#中,赋值我至少知道两种形式。

Assignment in F# has at least 2 forms that I am aware of.

// Assigning to a mutable value
let mutable v1 = 42
v1 <- 13

// Assigning to a ref cell
let v1 = ref 0
v1 := 42

当然,您应该绝对阅读Brian的文章。它非常详细,介绍了两种语言之间的翻译中的许多要点。

And of course, you should absolutely read Brian's article on this subject. It's very detailed and goes over many of the finer points on translating between the two languages

  • http://lorgonblog.spaces.live.com/Blog/cns!701679AD17B6D310!725.entry

这篇关于将C#代码转换为F#(如果声明)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆