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

查看:17
本文介绍了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()而不是printRandomunused".

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.

顺便说一句,使用单元编写调用的最常见方法是使用空格,尤其是在 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天全站免登陆