F#函数与值 [英] F# Functions vs. Values

查看:112
本文介绍了F#函数与值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常简单的问题,我只是想检查一下我在做什么以及如何解释F#是有意义的.如果我有声明

This is a pretty simple question, and I just wanted to check that what I'm doing and how I'm interpreting the F# makes sense. If I have the statement

let printRandom = 
  x = MyApplication.getRandom()
  printfn "%d" x
  x

F#不会创建 printRandom 作为一个函数,而是运行一次,然后为其分配一个值.因此,现在,当我调用printRandom时,无需获取新的随机值并打印它,而只是获得第一次返回的内容.我可以这样定义它:

Instead of creating printRandom as a function, F# runs it once and then assigns it a value. So, now, when I call printRandom, instead of getting a new random value and printing it, I simply get whatever was returned the first time. I can get around this my defining it as such:

let printRandom() = 
  x = MyApplication.getRandom()
  printfn "%d" x
  x

这是在无参数函数和值之间进行区分的正确方法吗?这对我来说似乎不理想.它对咖喱,成分等有影响吗?

Is this the proper way to draw this distinction between parameter-less functions and values? This seems less than ideal to me. Does it have consequences in currying, composition, etc?

推荐答案

查看此问题的正确方法是F#没有诸如无参数函数之类的东西.所有函数都必须带有参数,但是有时您并不在意它是什么,因此您可以使用()(类型为unit的单例值).您还可以创建如下函数:

The right way to look at this is that F# has no such thing as parameter-less functions. All functions have to take a parameter, but sometimes you don't care what it is, so you use () (the singleton value of type unit). You could also make a function like this:

let printRandom unused = 
  x = MyApplication.getRandom()
  printfn "%d" x
  x

或者这个:

let printRandom _ = 
  x = MyApplication.getRandom()
  printfn "%d" x
  x

但是()是表示您不使用该参数的默认方式.它向调用者表达这一事实,因为类型是 unit->.int 而不是'a->int ;以及对读者而言,因为呼叫站点是 printRandom()而不是 printRandom未使用" .

But () is the default way to express that you don't use the parameter. It expresses that fact to the caller, because the type is unit -> int not 'a -> int; as well as to the reader, because the call site is printRandom () not printRandom "unused".

实际上,所有的函数都采用一个参数并返回一个值这一事实.

Currying and composition do in fact rely on the fact that all functions take one parameter and return one value.

顺便说一句,用unit编写调用的最常见方法是使用空格,尤其是在F#的非.NET亲戚中,例如Caml,SML和Haskell.这是因为()是单例值,而不是像C#中那样的语法.

The most common way to write calls with unit, by the way, is with a space, especially in the non .NET relatives of F# like Caml, SML and Haskell. That's because () is a singleton value, not a syntactic thing like it is in C#.

这篇关于F#函数与值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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