`get` 函数参数顺序的基本原理
Rationale for order of arguments to `get` function
为什么参数按照 Array.get
和 Dict.get
中的顺序排列?大多数 map/filter 函数中的顺序是有道理的:函数出现在集合(或 monad,更普遍)之前。
MyCollection.map : (a -> b) -> MyCollection a -> MyCollection b
这样可以更轻松地在传入集合之前将较小的函数组合成较高的函数。
但是,为什么 index/key 在 get 函数中出现在集合之前?
Dict.get : comparable -> Dict comparable v -> Maybe v
似乎更难编写更高的功能。如果论点颠倒过来,可以这样写:
ids : List Int
myObjects : Dict Int a
selectObjects = List.map (Dict.get myObjects) ids
但是,我能想到的最好的写法是:
ids : List Int
myObjects : Dict Int a
selectObjects = List.map (\id -> (Dict.get id myObjects)) ids
我错过了什么吗? Array.get
、Dict.get
等参数顺序的原因是什么?
List.map (Dict.get myObjects) ids
不是函数组合。
作文是当你有
f : X -> Y
和
g : Y -> Z
然后你 组合 他们
h = f >> g
这样
h : X -> Z
现在,当像上面那样组合函数时,我们需要它们只需要一个参数。
所以在定义一个API时,问题是:
"When someone partially evaluates this function so that it can be composed, what is the last parameter they'll likely want to pass it?"
换句话说,我们是否更有可能看到这样的代码:
getStuff >> mungeIntoDict >> (Dict.get id)
或
getStuff >> getImportantId >> (Dict.get myDict)
?
答案是 "it depends"。 API 设计师做出了他们最好的猜测,当它不适合我们时,我们有 flip
。
为什么参数按照 Array.get
和 Dict.get
中的顺序排列?大多数 map/filter 函数中的顺序是有道理的:函数出现在集合(或 monad,更普遍)之前。
MyCollection.map : (a -> b) -> MyCollection a -> MyCollection b
这样可以更轻松地在传入集合之前将较小的函数组合成较高的函数。
但是,为什么 index/key 在 get 函数中出现在集合之前?
Dict.get : comparable -> Dict comparable v -> Maybe v
似乎更难编写更高的功能。如果论点颠倒过来,可以这样写:
ids : List Int
myObjects : Dict Int a
selectObjects = List.map (Dict.get myObjects) ids
但是,我能想到的最好的写法是:
ids : List Int
myObjects : Dict Int a
selectObjects = List.map (\id -> (Dict.get id myObjects)) ids
我错过了什么吗? Array.get
、Dict.get
等参数顺序的原因是什么?
List.map (Dict.get myObjects) ids
不是函数组合。
作文是当你有
f : X -> Y
和
g : Y -> Z
然后你 组合 他们
h = f >> g
这样
h : X -> Z
现在,当像上面那样组合函数时,我们需要它们只需要一个参数。
所以在定义一个API时,问题是:
"When someone partially evaluates this function so that it can be composed, what is the last parameter they'll likely want to pass it?"
换句话说,我们是否更有可能看到这样的代码:
getStuff >> mungeIntoDict >> (Dict.get id)
或
getStuff >> getImportantId >> (Dict.get myDict)
?
答案是 "it depends"。 API 设计师做出了他们最好的猜测,当它不适合我们时,我们有 flip
。