代码之家  ›  专栏  ›  技术社区  ›  Tim Robinson

使用list cons运算符(a::b)作为函数

  •  17
  • Tim Robinson  · 技术社区  · 14 年前

    F#允许您将运算符转换为函数,方法是使用 ( ) (+) 类型 int -> int -> int

    有没有可能用list cons操作符来做这个, :: ?

    它的行为不像普通的二进制运算符:

    FSI> (::);;
    
      (::);;
      -^^
    
    c:\temp\stdin(3,2): error FS0010: Unexpected symbol '::' in expression.
    Expected ')' or other token.
    

    以及 List.Cons

    (能够做到这一点很有用。例如,您可以使用它来实现 map in terms of fold ).

    3 回复  |  直到 14 年前
        1
  •  16
  •   Phillip Scott Givens Tatham Oddie    8 年前

    转述自 http://cs.hubfs.net/forums/permalink/11713/11713/ShowThread.aspx#11713

    (::) 是的有区别的联合“构造函数” list<'a> type ,因此提出了一个问题,即是否作为函数值,其参数是否应被current(例如 + )或tupled(像所有DU构造函数一样)。对于某些人来说,这两种方式都显得可疑/出乎意料,所以F#只是不允许这种构造。

    你当然可以写,例如。

    let cons x y = x :: y
    

    使用 cons ,或者只使用lambda fun x y -> x::y ,如果您想为此使用“curried prefix function of two args”(两个参数的curried前缀函数)。

        2
  •  6
  •   kvb    14 年前

    :: 不是运算符,而是根据语言语法的“符号关键字”(参见第节 3.6 of the spec ),也一样 :?> (*) (<@ @>) ).

        3
  •  4
  •   YotaXP    14 年前

    :: [] 两者都可以用 List<_>.Cons List<_>.Empty

    > List.Cons(4, List.Empty);;
    val it : int list = [4]
    
    > 4::[];;
    val it : int list = [4]
    
    > List<int>.Cons(4, List<int>.Empty);;
    val it : int list = [4]
    
    > List.Cons;;
    val it : 'a * 'a list -> 'a list = <fun:clo@24-7> //'
    
    > List<int>.Empty;;
    val it : int list = []