《Erlang 程序设计》练习答案 -- 第五章 记录与映射组

本文介绍如何使用Erlang解析JSON配置文件,并将其转换为映射,同时提供了一个搜索映射中符合条件元素的函数。还讨论了Erlang中可用的JSON解析工具。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

% (1).配置文件可以很方便地用 JSON 数据表示。
% 请编写一些函数来读取包含 JSON 数据的配置文件,
% 并将它们转换成 Erlang 的映射组。
% 再编写一些代码,对配置文件里的数据进行合理性检查。

注意:Erlang 并没有自带 Json 序列化函数
老爷子写的书上明明有,你说没有?戳 这里
这点也坑了我一下。

不过 StackOverFlow 答主给我们列出了两个 Erlang Json 序列化工具。
jiffyjsx

这里我用 rfc4627 这个序列化工具来解答,rfc4627 使用起来非常简单。
而且,据说 rfc4627 Json解析原本是想加入 Erlang 库里的。

先看下简单使用吧,gitclone下来后,当作我们平时写的模块用就好了。

其实内部有这些函数

% 配置文件比较简单,如下,如果是复杂的配置文件,代码需要更改
% {"cpu":"8"}
% {"memory":"8G"}
% {"disk":"1T"}

-module(parseFile).
-export([parse_file/1]).
-import(rfc4627, [decode/1, encode/1]).

parse_file(File) ->
    case file:open(File, read) of
        {ok, FileFd} -> parse_file(FileFd, io:get_line(FileFd, "Read a line"), #{});
        {error, Reason} -> io:format("parse_file/1 error:~p~n", [Reason])
    end.
% 非文件结尾
parse_file(FileFd, Line, X) when Line =/= eof ->
    case rfc4627:decode(Line) of
        {ok, {obj, [{Key, Value}]}, []} -> parse_file(FileFd, io:get_line(FileFd, "Read a line"), X#{Key => Value});
        {error, Reason} -> io:format("parse_file/3 error:~p~n", [Reason])
    end;
% 读到文件结尾
parse_file(FileFd, Line, X) when Line =:= eof ->
    file:close(FileFd),
    X.

注意:配置文件要是 .json 结尾,普通文件存储 json 格式有许多奇怪的问题。


% (2).编写一个 map_search_pred(Map, Pred) 函数,
% 让它返回映射组里第一个符合条件的 {Key, Value} 元素
% (条件是 Pred(Key, Vaule) 为 true)。

-module(mapsearchpred).
-export([map_search_pred/2, pred/2]).

map_search_pred(Map, Pred) ->
    map_search_pred(Map, maps:keys(Map), Pred).

map_search_pred(Map, [Key|T], Pred) ->
    case pred(Key, maps:get(Key, Map)) of
        true -> {Key, maps:get(Key, Map)};
        false -> map_search_pred(Map, T, Pred)
    end;
map_search_pred(Map, [], Pred) ->
    io:format("not found~n").

% 比较函数
pred(Key, Value) ->
    case (Key =:= Value) of
        true -> true;
        false -> false
    end.


% (3).高级练习:查找 Ruby 散列类的手册页。制作一个模块,
% 加入这个 Ruby 类里你认为适合的 Erlang 方法。 
% 这里我简单实现一个 计算元祖中元素出现的次数。

开放性题目,感兴趣大家自己去查查吧~。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夏天的技术博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值