簡體   English   中英

如何在erlang中使用記錄參數定義函數

[英]How to define function with record argument in erlang

我想定義函數輸入的結構。

這個模塊定義了我的功能(部分是偽代碼):

-module(my_service).
-export([my_function/2]).
-type my_enum() :: 1 | 2 | 5.
-record(my_record, {id = null :: string(), name = null :: string(), myType = null :: my_enum()}).
-spec my_function(MyValue#my_record) -> Result#my_record.
my_function(ClientRequest, MyValue) when is_record(Entry, my_record) ->
    Response = client:request(get, "http://www.example.com/api?value=" + MyValue#my_record.name),
    case Response of
        {ok, Status, Head, Body} ->
            Result = parse_response(Body, my_record);
        Error ->
            Error
    end.

這就是我的稱呼:

-module(test1).
-import(io, [format/2]).
main(_) ->
    application:start(inets),
    MyTestValue = #my_record{name => "test value", myType => 2},
    X = my_service:my_function(MyTestValue),
    io:format("Response: ~p", [X]).

那么,有什么主意我可以強制將函數輸入的類型設置為my_record類型嗎?

直接在函數參數列表中解構記錄通常很方便,這也會強制該參數具有所需的記錄類型。 例如,我們可以像這樣稍微修改my_function/2

my_function(ClientRequest, #my_record{name=Name}=MyValue) ->
    Response = client:request(get, "http://www.example.com/api?value=" ++ Name),
    case Response of
        {ok, Status, Head, Body} ->
            Result = parse_response(Body, MyValue);
        Error ->
            Error
    end.

請注意,我們如何對第二個參數MyValue模式匹配:我們不僅在斷言它是#my_record{}實例,而且還將其name字段同時提取到Name變量中。 這很方便,因為我們在函數正文的第一行上使用了Name 請注意,我們還保留參數名MyValue因為我們將其傳遞給函數體內的parse_response/2 如果我們不需要它,我們可以這樣編寫函數頭:

my_function(ClientRequest, #my_record{name=Name}) ->

這仍然具有強制第二個參數為#my_record{}類型的預期效果,並且仍將提取Name 如果需要,可以類似的方式提取其他字段:

my_function(ClientRequest, #my_record{name=Name, id=Id}) ->

然后, NameId都可以在函數體內使用。

另一件事:不要將atom null用作記錄字段的默認值。 Erlang記錄字段的默認值是原子undefined ,因此您應該使用它。 這比在語言中定義自己的null概念更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM