Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Bloody
Mar 3, 2013

gonadic io posted:

if you split that up using 'where' and use 'filter' instead of list comprehensions, it becomes a lot clearer imo

this is what i'd write it as (no actually I'd write it as data.list.sort which is a merge sort but let's ignore that for now). also i'd use data.list.partition instead of two separate filters but i'll leave that as an exercise
code:
qsort :: Ord a => [a] -> [a]
qsort [] = []
qsort (x:xs) = qsort lessThan ++ [x] ++ qsort greaterThan
    where
    lessThan = filter (< x) xs
    greaterThan = filter (>= x) xs
feel free to add extra parens if it makes it easier for you too.

this looks awesome as hell and i feel like i suddenly "get it" thanks

Adbot
ADBOT LOVES YOU

Gazpacho
Jun 18, 2004

by Fluffdaddy
Slippery Tilde
nothing i post should be interpreted as a sign of interest in or approval of the iverson tradition

Ericadia
Oct 31, 2007

Not A Unicorn

Bloody posted:

this looks awesome as hell and i feel like i suddenly "get it" thanks

agreed this has been pretty helpful. Everyone talkin bout haskell has been helpful in fact. thanks guys :3:

Athas
Aug 6, 2007

fuck that joker

Internet Janitor posted:

would there be actual interest in an APL/J/K thread in CoC, or would it just be pages and pages of "this is unreadable", "what's with the funny symbols", etc

Would read and participate! I have a colleague who works on a compiler for a statically typed APL dialect, and I hope to get involved at some point. It is an amazing language that I still do not understand fully.

Gazpacho posted:

arrays in haskell make me lol

Arrays in most languages make me lol, they all get it wrong! For example, Haskell's Data.Array lets you define the index space as all sorts of crazy things. The way you define an N-dimensional array is to define an array where an index is a tuple of N integers. But then you cannot efficiently perform partial indices, e.g. index that N-dimensional array with a single integer to get an (N-1)-dimensional array. Data.Vector isn't better as I remember it. And no, using arrays of arrays is not the same thing, we are not primitive C programmers here.

Arrays are surprisingly hard to get right, and I suspect they pretty much have to be a builtin to be both safe, performant, and expressive. (Fortran gets it right but gets so much more wrong.)

gonadic io
Feb 16, 2011

>>=

Athas posted:

Data.Vector isn't better as I remember it

Last I checked, Data.Vector makes your index be an int and so disallows N-dimensional arrays completely unless you do the conversation yourself or have arrays of arrays.

gonadic io
Feb 16, 2011

>>=
Have you seen Repa though? It's my understanding that it's based off of fortan's arrays and does allow efficient sectioning

Athas
Aug 6, 2007

fuck that joker

gonadic io posted:

Last I checked, Data.Vector makes your index be an int and so disallows N-dimensional arrays completely unless you do the conversation yourself or have arrays of arrays.

Yes, so it's like C. It's efficient, but not terribly expressive.

gonadic io posted:

Have you seen Repa though? It's my understanding that it's based off of fortan's arrays and does allow efficient sectioning

Yeah, Repa is better, but it's very notationally and conceptually heavyweight (it really pushes the type system), so still not nearly as nice as arrays in true array languages. For example, if you have a two-dimensional array of integers, you should be able to map a function that takes a single-dimensional array and produces an integer, and end up with a single-dimensional array (just like you can do with a list or array-of-arrays). This is not terribly nice to express in Repa.

gonadic io
Feb 16, 2011

>>=
Yeah, when I used Repa for image processing (calculating stereoscopic depth from two images taken side by side) a few years ago I really struggled with using Repa.

ahmeni
May 1, 2005

It's one continuous form where hardware and software function in perfect unison, creating a new generation of iPhone that's better by any measure.
Grimey Drawer
I had an interview today for a devops job that requires python and they asked me how I'd flip the keys and values in a dictionary and I came back with

code:

>>> a = {'x': 1, 'y': 2}
>>> {v:k for k,v in a.items()}
{1: 'x', 2: 'y'}

and it seemed to throw them a bit and they asked if I knew another way so I did

code:

>>> dict(zip(a.values(),a.keys()))
{1: 'x', 2: 'y'}

which also seemed awkward? can I chalk it up to writing code on a whiteboard is weird or did I miss some standard interview fizz buzz thing

Malcolm XML
Aug 8, 2009

I always knew it would end like this.

ahmeni posted:

I had an interview today for a devops job that requires python and they asked me how I'd flip the keys and values in a dictionary and I came back with

code:

>>> a = {'x': 1, 'y': 2}
>>> {v:k for k,v in a.items()}
{1: 'x', 2: 'y'}

and it seemed to throw them a bit and they asked if I knew another way so I did

code:

>>> dict(zip(a.values(),a.keys()))
{1: 'x', 2: 'y'}

which also seemed awkward? can I chalk it up to writing code on a whiteboard is weird or did I miss some standard interview fizz buzz thing

what happens if two keys map to the same value

Cybernetic Vermin
Apr 18, 2005

ahmeni posted:

I had an interview today for a devops job that requires python and they asked me how I'd flip the keys and values in a dictionary and I came back with

code:

>>> a = {'x': 1, 'y': 2}
>>> {v:k for k,v in a.items()}
{1: 'x', 2: 'y'}

and it seemed to throw them a bit and they asked if I knew another way so I did

code:

>>> dict(zip(a.values(),a.keys()))
{1: 'x', 2: 'y'}

which also seemed awkward? can I chalk it up to writing code on a whiteboard is weird or did I miss some standard interview fizz buzz thing

eh, i'd assume they expected a loop or such, and you just went more idiomatic than they saw coming, unless this is some very highly skilled job

tef
May 30, 2004

-> some l-system crap ->

MALE SHOEGAZE posted:

qntm posted:

Ruby was and remains a massive, massive, wholly welcome improvement on Bash scripting.

this would be true if the people who were replacing their bash scripts wrote them in ruby, instead of writing template bash scripts and filling them in with values from a yaml config file.

tef
May 30, 2004

-> some l-system crap ->

ahmeni posted:

I had an interview today for a devops job that requires python and they asked me how I'd flip the keys and values in a dictionary and I came back with

code:
>>> a = {'x': 1, 'y': 2}
>>> {v:k for k,v in a.items()}
{1: 'x', 2: 'y'}
and it seemed to throw them a bit and they asked if I knew another way so I did

code:
>>> dict(zip(a.values(),a.keys()))
{1: 'x', 2: 'y'}
which also seemed awkward? can I chalk it up to writing code on a whiteboard is weird or did I miss some standard interview fizz buzz thing

these both seem fine answers, the first more than the second.

often when they ask you to repeat things they're asking you to give the answer in front of them that may or may not be related to the question at hand.

qntm
Jun 17, 2009
Huh, so if a dictionary has duplicate values in it, values() will contain duplicates? Knowing that is going to save me a few puzzled hours one day.

Cybernetic Vermin
Apr 18, 2005

not sure what it would otherwise do, duplicate values should certainly be allowed, so stuffing them in a set would be pretty broken

The MUMPSorceress
Jan 6, 2012


^SHTPSTS

Gary’s Answer
So is the right answer some sort of dumb (in the complexity sense) foreach loop that turns duplicate keys into some type of list of values to deal with key collisions? Kinda like you would do with a hashtable?

MononcQc
May 29, 2007

If you wanted no loss of information whatsoever, I'd use the old values as new keys, but then the old keys would be stored as lists of values.

I haven't pythoned in like 4-5 years so bear with me

Python code:
dict = {"a": "b", "c":"d", "e":"b"}
flipped = {v:[] for v in dict.values()}
for k,v in dict.items():
    flipped[v].append(k)
which yields {'b': ['a', 'e'], 'd': ['c']}. You could probably do the thing in one pass by checking if the value exists and creating the list dynamically I guess.

Python code:
dict = {"a": "b", "c":"d", "e":"b"}
flipped = {}
for k,v in dict.items():
    if not v in flipped:
        flipped[v] = []
    flipped[v].append(k)

MononcQc fucked around with this message at 16:57 on Nov 30, 2015

The MUMPSorceress
Jan 6, 2012


^SHTPSTS

Gary’s Answer
that's what i figured. holy cow is python's syntax for that so much cleaner than what i'd do in a c-family language. it's too bad i've never found a good reason to learn python around here.

Soricidus
Oct 21, 2010
freedom-hating statist shill

MononcQc posted:

If you wanted no loss of information whatsoever, I'd use the old values as new keys, but then the old keys would be stored as lists of values.

I haven't pythoned in like 4-5 years so bear with me

Python code:
dict = {"a": "b", "c":"d", "e":"b"}
flipped = {v:[] for v in dict.values()}
for k,v in dict.items():
    flipped[v].append(k)
which yields {'b': ['a', 'e'], 'd': ['c']}. You could probably do the thing in one pass by checking if the value exists and creating the list dynamically I guess.

Python code:
dict = {"a": "b", "c":"d", "e":"b"}
flipped = {}
for k,v in dict.items():
    if not v in flipped:
        flipped[v] = []
    flipped[v].append(k)

collections.defaultdict(list) maybe

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder
really don't understand why python doesn't have built-ins for really common things like reversing hashes, flattening lists, etc.

Cybernetic Vermin
Apr 18, 2005

LeftistMuslimObama posted:

that's what i figured. holy cow is python's syntax for that so much cleaner than what i'd do in a c-family language. it's too bad i've never found a good reason to learn python around here.

pfft, python is so wordy, the k solution is far more elegant (e.g. for d:`a`b`c`d`e!1 2 1 1 2 the result is 1 2!(`a`c`d;`b`e)):

code:
(!d)@=. d
oK from a few pages back depress me by seemingly not allowing indexing an array with a dictionary, though it may be some K5 change which i am unaware of

(actually the map/last-builder syntax of python and others is one of those syntactic conveniences which is right up there with pattern matching in how surprisingly helpful and comprehensible it is; there is a reason why nerd favorites tend to have both)

weird
Jun 4, 2012

by zen death robot
code:
(loop with flipped = (make-hash-table)
   for value being the hash-values of h using (hash-key key)
   do (push key (gethash value flipped))
   finally (return flipped))

leftist heap
Feb 28, 2013

Fun Shoe
lol throw the loop macro in the trash where it belongs

Jerry Bindle
May 16, 2003
the loop macro is what soured me, for better or worse, off of common lisp. it seemed to be the best way to do iterative things in common lisp, but its it's own weird non lispy dsl. when i write lisp i want to write lisp :mad:

MononcQc
May 29, 2007

dict:fold(fun(K,V,D) -> dict:append(V,K,D) end, dict:new(), Dict) v:shobon:v

leftist heap
Feb 28, 2013

Fun Shoe
clojure has it built in apparently and its basically the same impl as ^^

code:
(defn map-invert
  "Returns the map with the vals mapped to the keys."
  {:added "1.0"}
  [m] (reduce (fn [m [k v]] (assoc m v k)) {} m))

Soricidus
Oct 21, 2010
freedom-hating statist shill

MALE SHOEGAZE posted:

really don't understand why python doesn't have built-ins for really common things like reversing hashes, flattening lists, etc.

are these things really all that common?

i mean that's not an argument against having a built-in, given that it does come with implementations of other not-particularly-common things, and it's dumb when they actively refuse to add that kind of thing because "it's only a one-liner to implement it yourself", but you can see how they'd slip through the net

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
okay, now someone do the map flip thing with brainfuck

Malcolm XML
Aug 8, 2009

I always knew it would end like this.

MononcQc posted:

If you wanted no loss of information whatsoever, I'd use the old values as new keys, but then the old keys would be stored as lists of values.

I haven't pythoned in like 4-5 years so bear with me

Python code:

dict = {"a": "b", "c":"d", "e":"b"}
flipped = {v:[] for v in dict.values()}
for k,v in dict.items():
    flipped[v].append(k)
which yields {'b': ['a', 'e'], 'd': ['c']}. You could probably do the thing in one pass by checking if the value exists and creating the list dynamically I guess.

Python code:

dict = {"a": "b", "c":"d", "e":"b"}
flipped = {}
for k,v in dict.items():
    if not v in flipped:
        flipped[v] = []
    flipped[v].append(k)

yeah this is correct or at least more correct

inverting a finite dict only works if the dict represents an injective function
e:
and defaultdict (of lists) encapsulates the check if exists logic

Malcolm XML
Aug 8, 2009

I always knew it would end like this.

MALE SHOEGAZE posted:

really don't understand why python doesn't have built-ins for really common things like reversing hashes, flattening lists, etc.

there's a lot of dumb tricks in the itertools documentation

weird
Jun 4, 2012

by zen death robot

Barnyard Protein posted:

the loop macro is what soured me, for better or worse, off of common lisp. it seemed to be the best way to do iterative things in common lisp, but its it's own weird non lispy dsl. when i write lisp i want to write lisp :mad:

format owns too

Jerry Bindle
May 16, 2003

weird posted:

format owns too

yeah format gets a pass with me because i can understand how to use it

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder

Soricidus posted:

are these things really all that common?

i don't really reverse hashes that much, and when I do I usually want to handle collisions on my own.

If flattening a list is not a common thing, then I'm programming wrong. Anyhow, these were just two examples, there are tons of other things that python really seems to be lacking to me. I don't have a list though, because I don't write python that much. I just know that I'm frequently copy + pasting basic things from stack overflow.

The MUMPSorceress
Jan 6, 2012


^SHTPSTS

Gary’s Answer
Here's a (sort of) map inversion in MUMPS, where the original map was a single-layer tree with subscript=key and the value of the subscript=value:
code:
flipIt n arr,cur,name,int
	s arr(1)="Hi",arr(2)="Ho",arr(3)="There",arr(4)="Neighbor",arr(5)="Hi"
	;
	f  s cur=$o(arr(cur)) q:cur=""  d
	. q:cur="new"
	. s name=$na(arr("new",arr(cur)))
	. i '$d(@name) d
	. . s @name=1,@name@(@name)=cur
	. e  d
	. . s @name=@name+1,@name@(@name)=cur
	m int=arr("new")
	k arr
	n arr
	m arr=int
	s cur=$na(arr)
	f  s cur=$q(@cur) q:cur=""  d
	. w cur,"=",@cur,!
	;
	q
And the output:
code:
arr("Hi")=2
arr("Hi",1)=1
arr("Hi",2)=5
arr("Ho")=1
arr("Ho",1)=2
arr("Neighbor")=1
arr("Neighbor",1)=4
arr("There")=1
arr("There",1)=3
I use the key-level subscript as a counter for the number of values mapped to that key, and use the integer subscripts as the indices into the values. That way you can just loop over the number of values listed in the key.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."

Cybernetic Vermin posted:

oK from a few pages back depress me by seemingly not allowing indexing an array with a dictionary, though it may be some K5 change which i am unaware of

It's a K5 limitation, I'm afraid. Many things have been aggressively simplified compared to K4.
There's still a reasonably simple K5 formulation.

No repeat values:
code:
{(.x)!!x}
Group keys with duplicate values into a list in the result:
code:
{(?.x)!(!x)@.=.x}

VikingofRock
Aug 24, 2008




Python really should have a deep_flatten() somewhere (probably in itertools) because of the pitfalls with strings.

qntm
Jun 17, 2009
In Perl it's

Perl code:
%h = reverse %h;

ahmeni
May 1, 2005

It's one continuous form where hardware and software function in perfect unison, creating a new generation of iPhone that's better by any measure.
Grimey Drawer
thanks for the feedback folks, apparently I did well and am through tithe next round of garbage: an "aptitude test" and some on-site pairing with people to do some technical work? the first I've done before and they're terrible, the second sounds neat but weird

Captain Foo
May 11, 2004

we vibin'
we slidin'
we breathin'
we dyin'

ahmeni posted:

thanks for the feedback folks, apparently I did well and am through tithe next round of garbage: an "aptitude test" and some on-site pairing with people to do some technical work? the first I've done before and they're terrible, the second sounds neat but weird

aptitude install job-ng

Adbot
ADBOT LOVES YOU

MononcQc
May 29, 2007

ahmeni posted:

thanks for the feedback folks, apparently I did well and am through tithe next round of garbage: an "aptitude test" and some on-site pairing with people to do some technical work? the first I've done before and they're terrible, the second sounds neat but weird

What kind of aptitude test? Like "are you skilled enough" tests or "what's your personality type" tests? both are terrible but for various reasons.

Pairing is time-consuming, but I don't hate it. lt lets you have a look at who you'll work with and how they are. You're interviewing them as much as they interview you in there, so try to avoid stuff like "let me show them how great I am" and try to make it more like your everyday work interaction with them. Otherwise they'll be observing you, but you won't be getting your part back.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply