Elixir确保值不是0或零

问题描述 投票:0回答:2

在这个函数中,我需要检查“price”变量是0还是nil才能通过执行priceFloat = price / 1将其转换为float,否则我会得到算术错误。

  def insert_product_shop(conn, product_id, shop_id, price) do
    IO.inspect(price, label: "price")
    priceFloat = price / 1 
    changeset = Api.ProductShop.changeset(%Api.ProductShop{p_id: product_id, s_id: shop_id, not_in_shop_count: 0, price: priceFloat})
    errors = changeset.errors
    valid = changeset.valid?
    case insert(changeset) do
      {:ok, product_shop} ->
        {:ok, product_shop}
      {:error, changeset} ->
        {:error, :failure}
    end
  end

这样做的惯用方法是什么?

我试过这个,但我仍然得到算术错误:

  def insert_product_shop(conn, product_id, shop_id, price) do
    IO.inspect(price, label: "price")
    case {price} do 
      {price} when price > 0 ->
        priceFloat = price / 1 
        changeset = Api.ProductShop.changeset(%Api.ProductShop{p_id: product_id, s_id: shop_id, not_in_shop_count: 0, price: priceFloat})
        errors = changeset.errors
        valid = changeset.valid?
        case insert(changeset) do
          {:ok, product_shop} ->
            {:ok, product_shop}
          {:error, changeset} ->
            {:error, :failure}
        end
      end
  end
elixir elixir-framework
2个回答
4
投票

你的代码不起作用的原因是因为在Elixir中,nil > 0是真的。你可以这样做:

if price not in [0, nil] do
  ...
else
  ...
end

要么

if is_number(price) and price > 0 do
  ...
else
  ...
end

2
投票

执行此操作的惯用方法是直接在函数子句中进行模式匹配:

def insert_product_shop(conn, product_id, shop_id, price)
  when not is_number(price), do: {:error, :nil}
def insert_product_shop(conn, product_id, shop_id, price)
  when price <= 0, do: {:error, :not_positive}
def insert_product_shop(conn, product_id, shop_id, price) do
  priceFloat = price / 1
  changeset = 
    Api.ProductShop.changeset(
      %Api.ProductShop{p_id: product_id,
                       s_id: shop_id,
                       not_in_shop_count: 0,
                       price: priceFloat})
  errors = changeset.errors
  valid = changeset.valid?

  case insert(changeset) do
    {:ok, product_shop} ->
      {:ok, product_shop}
    {:error, changeset} ->
      {:error, :failure}
  end
end

前两个条款可能会与一名警卫合并为一个

when not is_number(price) or price <= 0
© www.soinside.com 2019 - 2024. All rights reserved.