如何在函数式编程中增加一个变量 [英] how to increment a variable in functional programming

查看:123
本文介绍了如何在函数式编程中增加一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如,我想要这样做:

如何在函数式编程语言中增加一个变量?

  main :: IO()
main = do
let i = 0
i = i + 1
print i

预期输出:1。 简单的方法是引入一个变量名称的阴影:

  main: :IO()
main = do
let i = 0
let j = i
let i = j + 1
print i

打印 1 。只要写 let i = i + 1 不起作用,因为让在Haskell中使递归 >定义 - 它实际上是Scheme的 letrec

因此 i 在的右边> let i = i + 1 在这个等式的左边指的是 i - 不是到上层 i code>可能是预期的。阴影处理。



如何思考功能



这里要理解的一件事是功能使用纯的编程 - 不可变 - 值迫使我们在我们的代码中 make time 显式



在命令式设置中,时间是隐含的。我们改变我们的变数 - 但任何变化都是顺序。我们永远不会改变刚才var 的内容 - 只有它



在纯函数式编程中,这只是明确的。其中一种最简单的形式是在命令式编程中将值列表用作 连续变化记录 。更简单的是使用不同的变量来表示实体在不同时间点的不同值(参见 静态单一赋值表单 或SSA)。

How do you increment a variable in a functional programming language?

For example, I want to do:

main :: IO ()
main = do
    let i = 0
    i = i + 1
    print i

Expected output: 1.

解决方案

Simple way is to introduce shadowing of a variable name:

main :: IO ()
main = do
    let i = 0
    let j = i
    let i = j+1
    print i

Prints 1. Just writing let i=i+1 doesn't work because let in Haskell makes recursive definitions - it is actually Scheme's letrec.

So i in right-hand side of let i=i+1 refers to i in left hand side of this equation - not to the upper level i as might be intended. Shadowing takes care of that.

How to "think functional"

One thing to understand here is that functional programming with pure - immutable - values forces us to make time explicit in our code.

In imperative setting time is implicit. We "change" our vars - but any change is sequential. We can never change what that var was a moment ago - only what it will be from now on.

In pure functional programming this is just made explicit. One of the simplest forms this can take is with using lists of values as records of sequential change in imperative programming. Even simpler is to use different variables altogether to represent different values of an entity at different points in time (cf. static single assignment form, or SSA).

这篇关于如何在函数式编程中增加一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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