获取记录列表并执行groupby操作的Elm函数定义是什么样的(参见下面的示例)?使用SQL类比,我基本上试图在Elm中实现select last, sum(age) from table group by last
。
[{name= "John", last= "Smith", age= 10}
,{name="Jason", last= "Smith", age= 9}
, {name="Jane", last ="White", age =5}]
return [{last="Smith", age =19},
{last ="White", age =5}]
答案 0 :(得分:5)
您可以使用Dict.Extra.groupBy
执行初始分组,然后通过映射列表并总结年龄来对年龄进行求和:
import Dict.Extra exposing (groupBy)
familySumAges : List Person -> List Family
familySumAges =
groupBy .last
>> Dict.map (\_ -> List.map .age >> List.sum)
>> Dict.toList
>> List.map (uncurry Family)
答案 1 :(得分:4)
以下答案由来自Elm Slack频道的@ holy-meekrob和@ilias提供。 https://ellie-app.com/7tqY9w6gNa1/1
module Main exposing (..)
import Dict exposing (..)
import Html exposing (text)
type alias Person =
{ name : String
, last : String
, age : Int
}
type alias Family =
{ last : String
, age : Int
}
people : List Person
people =
[ { name = "John"
, last = "Smith"
, age = 10
}
, { name = "Jason"
, last = "Smith"
, age = 9
}
, { name = "Jane"
, last = "White"
, age = 5
}
]
sumAges : Person -> Dict String Family -> Dict String Family
sumAges person families =
Dict.update
person.last
(\family ->
case family of
Nothing ->
Just { last = person.last, age = person.age }
Just fam ->
Just { last = person.last, age = fam.age + person.age }
)
families
main =
text (toString (List.foldl sumAges Dict.empty people |> Dict.values))
答案 2 :(得分:2)
我的方法与您接受的解决方案不同。
如果对记录列表进行了排序,那么只要姓氏保持不变,我们就可以简单地聚合年龄。 否则,我们需要为看不见的姓氏创建新记录。
p
我们基本上遍历所有人lst
并将它们添加到列表p::lst
的第一个元素,除非我们第一次遇到该姓氏,然后我们将其添加到data = [{name= "John", last= "Smith", age= 10},{name="Jason", last= "Smith", age= 9}, {name="Jane", last ="White", age =5}]
SumByLast data
< / p>
用
测试.last
显然,如果我们将.age
和father = begin
pdf_father = p.pdf(father)
son = multiNormal(father, mulN_cov).rvs(1)
pdf_son = p.pdf(son)
作为参数传递,则此功能可以是通用的