初学者:F#中的表达

时间:2016-01-20 19:21:15

标签: f# functional-programming

我想改写这个

//finds the max of 3 numbers
let max3 (n1, n2, n3) = let mx1 = if (n1 > n2) then n1 else n2 in if (mx1 > n3) then mx1 else n3;

不使用"在"

我想出了这个

let max3 (n1, n2, n3) = 
   let mx1 = 
      if (n1 > n2) 
      then n1 
      else n2
   let mx2=
      if (mx1 > n3) 
      then mx1 
      else n3;;

表示未完成并希望表达。

不确定原因。 mx2支持获取更高的集合值并将其移动到其范围内的下一个函数。

我也希望能够这样做,以便我不使用任何let表达式。请理解这种语言的任何帮助都非常友好

编辑:任何人都可以回答我的问题吗?在F#中使用任何let表达式也可能出现这样的问题吗?

2 个答案:

答案 0 :(得分:5)

let max3 (n1, n2, n3) = max n1 (max n2 n3)
// val max3 : n1:'a * n2:'a * n3:'a -> 'a when 'a : comparison

max3 (13,4,7) 

最大值是为2个参数预定义的,可以按上述方式组成。 如果您声明没有类型,那么它将是通用的约束,类型'a需要具有比较函数。

在F#中,函数参数通常不是像(n1,n2,n3)那样的元组, 相反,它可以定义为

 let max3 n1 n2 n3 = max n1 (max n2 n3)
 // val max3 : n1:'a -> n2:'a -> n3:'a -> 'a when 'a : comparison

 max3 13 4 7 

答案 1 :(得分:3)

  

说,未完成,并期待一个表达。   不知道为什么。 mx2支持获取更高的集合值并将其移动到其范围内的下一个函数。

关于这个具体问题。每个函数都必须返回一些值。函数中的最后一个“表达式”被认为是该函数的返回值。

let foo a b c = 
    let x = a + b
    y + c

此处,y + c是最后一个表达式,它的值是函数foo的“返回值”。

但是,声明和绑定某个值(let x = a + b)是一个语句,而不是表达式,并且它没有任何值,因此以下代码将无法编译。

let foo a b c = 
    let result = a + b + c

如果要在原始代码中返回mx2的值,则必须将绑定语句(let mx2 = ...)转换为表达式:

let max3 (n1, n2, n3) = 
    let mx1 = ...

    if (mx1 > n3) 
    then mx1 
    else n3
相关问题