可以用无点式表达吗? [英] Can this be expressed in point free style?

查看:82
本文介绍了可以用无点式表达吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下表达式以将一个IEnumerable数字相加:

let sum l = l |> Seq.reduce(+)  //version a

是否有可能消除这种争论?

let sum = Seq.reduce(+)    //version b

我从F#编译器(FS0030)中得到一个错误,我似乎想起曾经看到过有关"eta转换"的事情,但不幸的是,我对lambda calc的了解太有限,无法跟踪eta转换是如何进行的.

可以像版本b中那样消除参数吗?

请问我有哪些文献可以解释eta转换以及如何在这段特定代码中发挥作用吗?

FS0030:

stdin(1,5):错误FS0030:值限制.值总和"为 推断具有通用类型 val sum:('_a-> int)当'_a:> seq时,要么将'sum'的参数设为显式,要么,如果您不希望使用 通用,添加类型注释.

解决方案

"Eta转换"仅表示添加或删除参数.您遇到的问题称为价值限制.在ML语言中,将值声明为值,即.没有显式参数声明的变量,即使具有函数类型,也不能具有泛型类型. 此处是一些相关文献.这样做的目的是防止ref单元保存不同类型的值.例如,在没有价值限制的情况下,将允许以下程序:

let f : 'a -> 'a option =
    let r = ref None
    fun x ->
        let old = !r
        r := Some x
        old

f 3           // r := Some 3; returns None : int option
f "t"         // r := Some "t"; returns Some 3 : string option!!!

正如kvb所说,如果您不希望该函数具有通用性,则可以添加类型签名并使用无点样式.

Given the following expression to sum an IEnumerable of numbers:

let sum l = l |> Seq.reduce(+)  //version a

is it possible to eliminate the argument--like so?

let sum = Seq.reduce(+)    //version b

I get an error from the F# compiler (FS0030) and I seem to recall having seen something about an "eta conversion" being involved but unfortunately my knowledge of lambda calc is too limited to follow how eta conversion is involved.

Can the argument be eliminated as in version b?

Would someone please point me to literature that would explain an eta conversion and how it would come into play in this particular piece of code?

FS0030:

stdin(1,5): error FS0030: Value restriction. The value 'sum' has been inferred to have generic type val sum : ('_a -> int) when '_a :> seq Either make the arguments to 'sum' explicit or, if you do not intend for it to be generic, add a type annotation.

解决方案

"Eta conversion" simply means adding or removing the argument. The problem you are hitting is called value restriction. In ML languages, a value declared as a value, ie. declared without explicit arguments, cannot have a generic type, even if it has a function type. Here is some relevant literature. The idea is to prevent a ref cell from holding values of different types. For example, without value restriction, the following program would be allowed:

let f : 'a -> 'a option =
    let r = ref None
    fun x ->
        let old = !r
        r := Some x
        old

f 3           // r := Some 3; returns None : int option
f "t"         // r := Some "t"; returns Some 3 : string option!!!

As kvb said, if you do not intend the function to be generic, then you can add a type signature and use point-free style.

这篇关于可以用无点式表达吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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