These are chat archives for evhub/coconut

21st
Mar 2018
Vikram Kalabi
@vikramkalabi
Mar 21 2018 06:00
@evhub @eindiran Thanks.
Vikram Kalabi
@vikramkalabi
Mar 21 2018 06:30
How can I acheive reduce by key functionality in coconut? Specifically I want to do this:
input: [(1, [2]), (1, [3])] 
output: [(1, [2, 3])]
Evan Hubinger
@evhub
Mar 21 2018 18:23

@vikramkalabi I might do

from collections import defaultdict
join_pairs = reduce$((def (acc, (k, v)) ->
    acc[k] += v;
    acc
), ?, defaultdict(list))

though I admit that's not very pretty. Any other ideas? Maybe a new builtin is warranted here?

Evan Hubinger
@evhub
Mar 21 2018 18:28
You could also write it recursively as
from collections import defaultdict
def join_pairs2([]) = defaultdict(list)
@addpattern(join_pairs2)
def join_pairs2([(k, v)] + tail) =
    result = join_pairs2(tail)
    result[k] += v
    result
Elliott Indiran
@eindiran
Mar 21 2018 18:29
This is a case where I would like use the standard python solution: for-loop and defaultdict
although I like @evhub's recursive solution
do you need to preserve the ordering of the original list?
Jeffrey Benjamin Brown
@JeffreyBenjaminBrown
Mar 21 2018 19:45
This feels like the kind of problem that folding solves. My Google-Fu is failing me, though -- does Coconut have an equivalent to Haskell's fold functions?
Evan Hubinger
@evhub
Mar 21 2018 19:59
@JeffreyBenjaminBrown reduce = foldl (with different argument order). If you want foldr instead, you can just do
def foldr(func, init, xs) =
    reduce((x, y) -> func(y, x), reversed(xs), init)
Jeffrey Benjamin Brown
@JeffreyBenjaminBrown
Mar 21 2018 20:00
Nice!