我想编写一个将自定义类型编码Decision a为JSON 的函数。该a标签可以是如Accept或Reject,我想我的函数调用取决于标签的类型等功能。
我曾尝试case ... of根据Decision类型和标记来编写该语句,但无法获得两种工作方式。
这是我的类型:
type Decision a
= Decision Metadata a
type Accepted
= Accepted AcceptDetails
type Rejected
= Rejected RejectDetails
type alias Metadata =
{ time : Time.Posix }
type alias AcceptDetails =
{ comment : String }
type alias RejectDetails =
{ reasonCode : Int }
Run Code Online (Sandbox Code Playgroud)
现在,我想写一个可以做出两种决定的编码器。类似于以下内容:
encoder : Decision a -> Json.Encode.Value
encoder decision =
case decision of
Decision _ (Accepted _) …Run Code Online (Sandbox Code Playgroud) 我想计算数字列表中连续元素的差异,例如input = [1, 2, 3, 5]应该给出输出[-1, -1, -2]。
我想出了两种看起来或多或少复杂的方法。有没有更简单、更惯用的方法来做到这一点?
使用邮政编码:
Enum.zip(input, Enum.drop(input,1))
|> Enum.map(fn {x,y} -> x-y end)
Run Code Online (Sandbox Code Playgroud)
使用扫描(太复杂):
Enum.scan(input, [0, 0], fn x, [_delta, prev] -> [prev-x, x] end)
|> Enum.map(fn [x, _y] -> x end)
|> Enum.drop(1)
Run Code Online (Sandbox Code Playgroud)