gpt4 book ai didi

list - Erlang 记录项列表

转载 作者:行者123 更新时间:2023-12-04 13:54:58 25 4
gpt4 key购买 nike

例如我有erlang记录:

-record(state, {clients
}).

我可以从客户字段列表中制作吗?

我可以像正常列表一样保留在客户中吗?我怎样才能在这个列表中添加一些值?

谢谢你。

最佳答案

也许你的意思是:

-module(reclist).
-export([empty_state/0, some_state/0,
add_client/1, del_client/1,
get_clients/1]).

-record(state,
{
clients = [] ::[pos_integer()],
dbname ::char()
}).

empty_state() ->
#state{}.

some_state() ->
#state{
clients = [1,2,3],
dbname = "QA"}.

del_client(Client) ->
S = some_state(),
C = S#state.clients,
S#state{clients = lists:delete(Client, C)}.

add_client(Client) ->
S = some_state(),
C = S#state.clients,
S#state{clients = [Client|C]}.

get_clients(#state{clients = C, dbname = _D}) ->
C.

测试:
1> reclist:empty_state().
{state,[],undefined}
2> reclist:some_state().
{state,[1,2,3],"QA"}
3> reclist:add_client(4).
{state,[4,1,2,3],"QA"}
4> reclist:del_client(2).
{state,[1,3],"QA"}
::[pos_integer()]表示字段的类型是一个正整数值列表,从 1开始;这是分析工具的提示 dialyzer ,当它执行类型检查时。

Erlang 还允许您在记录上使用模式匹配:
5> reclist:get_clients(reclist:some_state()).
[1,2,3]

进一步阅读:
  • Records
  • Types and Function Specifications
  • dialyzer(1)


  • @只是我的正确意见 answer让我记得我喜欢 Haskell 如何获取数据类型中字段的值。

    这是一个数据类型的定义,从 Learn You a Haskell for Great Good! 偷来的。 ,它利用记录语法:
    data Car = Car {company :: String 
    ,model :: String
    ,year :: Int
    } deriving (Show)

    它创建函数 company , modelyear ,即在数据类型中查找字段。我们先造一辆新车:
    ghci> Car "Toyota" "Supra" 2005
    Car {company = "Toyota", model = "Supra", year = 2005}

    或者,使用记录语法(字段的顺序无关紧要):
    ghci> Car {model = "Supra", year = 2005, company = "Toyota"}
    Car {company = "Toyota", model = "Supra", year = 2005}
    ghci> let supra = Car {model = "Supra", year = 2005, company = "Toyota"}
    ghci> year supra
    2005

    我们甚至可以使用模式匹配:
    ghci> let (Car {company = c, model = m, year = y}) = supra
    ghci> "This " ++ c ++ " " ++ m ++ " was made in " ++ show y
    "This Toyota Supra was made in 2005"

    我记得有人尝试在 Erlang 中实现类似于 Haskell 的记录语法的东西,但不确定它们是否成功。

    一些关于这些尝试的帖子:
  • In Response to "What Sucks About Erlang"
  • Geeking out with Lisp Flavoured Erlang .但是我会在这里忽略参数化模块。

  • 当您想要创建某个结构的新值时,LFE 似乎使用了类似于提供 Scheme 的宏(例如 Racket):
    > (define-struct car (company model year))
    > (define supra (make-car "Toyota" "Supra" 2005))
    > (car-model supra)
    "Supra"

    我希望我们将来会有一些接近 Haskell 记录语法的东西,这将非常实用和方便。

    关于list - Erlang 记录项列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4953775/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com