Skip to content

Instantly share code, notes, and snippets.

@okabe-yuya
Last active August 22, 2021 02:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okabe-yuya/9317abc95e8583795e450815aef26aca to your computer and use it in GitHub Desktop.
Save okabe-yuya/9317abc95e8583795e450815aef26aca to your computer and use it in GitHub Desktop.
構造体へのFunctor / fmapのオリジナル定義
defmodule Product do
defstruct name: "", price: 0
def fmap(func, %Product{ name: name, price: price }) do
{ n_name, n_price } = func.(name, price)
%Product{ name: n_name, price: n_price }
end
end
stones = %Product{ name: "大人気!その辺に落ちていた石の詰め合わせ", price: 2000 }
summer_sale = Product.fmap(fn name, price -> { "[SummerSale]: #{name}", price - 200 } end, stones)
# %Product{
# name: "[SummerSale]: 大人気!その辺に落ちていた石の詰め合わせ",
# price: 1800
# }
price_hike = Product.fmap(fn name, price -> { "[市場価格高騰]: #{name}", price + 2000 } end, stones)
# %Product{
# name: "[市場価格高騰]: 大人気!その辺に落ちていた石の詰め合わせ",
# price: 4000
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment