Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

A concept in K that I wish more languages had is indexing with a list of indices. It always blows peoples' minds when I tell them how sorting works in K. You use grade (<) to return the indices that will sort the array if indexed in that order. Then you pass in that list as the indices to the list. They do it in the string examples in this tutorial.


Sorting a list by getting the sorted indices (permutation) and then applying them might seem a bit roundabout at first glance. Then you realize that you can apply the permutation to something else. For example, to sort a table by the values of a column, you get the column, "sort" the column, then apply the permutation to the original table (all columns of the table).


Another great concept is that function application and array indexing has the same syntax.

    a.map(f)
is basically† just:

    f[a]
and:

    a.map(x => m[x])
is still just:

    m[a]

†: Rank notwithstanding. If that bothers you that f might take an atom, pretend I said f@/:a and m@/:a instead.


A related operator is group (=), which creates a map between the unique elements of a list to their locations.

     x: 10 ? `a`b`c
     x
    `a`c`c`c`c`a`b`a`a`c
     =x
    a|0 5 7 8  
    b|,6       
    c|1 2 3 4 9


How does grade work? Can you customize how it ranks results?


If you want to rank results differently, you'd apply a function to each element of the original vector that computes the rank / weight of that element. Then you sort by weights, and apply the result to the original vector. Something like:

input[<{...compute weight of element x...}'input]


This is also how filtering works, you map a function that returns 0 or 1 over the list. Then you can call where (&) and it will give you the indices where the function evaluates true. Index by that and you'll filter a list.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: