添加到Erlang中的现有值 [英] Adding to an existing value in Erlang

查看:86
本文介绍了添加到Erlang中的现有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个将数字存储到记录中的函数,然后在函数运行时将值X添加到该数字。

I am attempting to create a function that stores a number into a record and then adds value X to that number every time the function runs.

Value: 5
Run Function (Add One):   1
Value should be: 6
Run Function (Add One):   1
value should be 7

我尝试使用记录:

-record(adder,{value :: integer()}).

---function 
   Number = random:uniform(6),
        L=#added{value = Number + #added.value}.

这不起作用,因为它每次都会重置值。任何建议?

This does not work as it resets the value every time. Any suggestions?

推荐答案

看看这段代码:

-module(test).
-export([add/1]).

-record(adder, {value=6}).

add(X) ->
    #adder{value = X + #adder.value}.

如果您在shell中编译,任何对add(3)的调用将导致 {adder,5},而不在{adder,9}中。看看:

If you compile this in your shell, any call to "add(3)" will result in "{adder,5}" and not in "{adder, 9}". Take a look:

Eshell V6.4  (abort with ^G)
1> c(test).
{ok,test}
2> test:add(3).
{adder,5}
3> test:add(3).
{adder,5}

怎么来?这是因为记录实际上是元组。最后一行中的表达式#adder.value被计算为加法器元组中的字段值的位置,这是2.我们有一些证明。更改记录的定义:

How come? This is because records are actually tuples. The expression "#adder.value" in the last line is evaluated as the position of the field "value" in your adder tuple, which is 2. Let's have some proof. Change the definition of your record:

-module(test).
-export([add/1]).

-record(adder, {field1, field2, value=6}).

add(X) ->
    #adder{value = X + #adder.value}.

现在,重新编译代码并再次调用add(3)会导致

Now, recompiling your code and calling add(3) again would result in

1> c(test).
{ok,test}
2> test:add(3).
{adder,undefined,undefined,7}

我问自己,你怎么样提出了这个问题。你不希望你的功能是这样的吗?

I've asked myself, how you came up with this question. Didn't you want your function to be something like this?

add2(#adder{value = V} = R, X) ->
    R#adder{value = V + X}.

这篇关于添加到Erlang中的现有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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