[英]How to typespec guards in a human friendly way?
我在玩守衛,我希望我的守衛定義也有一個類型規范:
defmodule AuctionHouse.Shared.ExtraGuards do
@moduledoc """
Contains additional guards to use in functions.
"""
defguard is_pos_integer(value) when is_integer(value) and value > 0
end
所以,現在我有了這個簡單的守衛,我想要它的規格。 然而,dyalizer 的建議並不完全是人類可讀的。
@spec is_pos_integer(any) ::
{:__block__ | {:., [], [:andalso | :erlang, ...]}, [],
[{:= | {any, any, any}, list, [...]}, ...]}
defguard is_pos_integer(value) when is_integer(value) and value > 0
我相信這可能被定義為一個 function ,它接受any
作為參數,但返回類型對我來說很難理解。 我認為這意味着它會創建 erlang 代碼,就像一個宏,但我無法理解它。
你得到的建議規范是這樣的,因為它是 guard 返回的 AST的規范,因為 guard 是一個隱藏在引擎蓋下的宏。 從本質上講,這意味着您向守衛傳遞了一些代碼(不是值),並取回了一些其他代碼。
簡短的回答是你可能不想輸入這個。 正確的類型規范可能是這樣的:
@spec is_pos_integer(Macro.t()) :: Macro.t()
這不是很有用。 我可能 go 沒有規范我們在 Elixir 的標准庫本身中采用相同的方法。 例如, Integer.is_odd/1
是一個與這里的is_pos_integer/1
非常相似的守衛,我們沒有關於它的規范。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.