Search code examples
j

Function composition in J


This is a pretty simple question but I can't seem to find an answer anywhere -- to map a list of numbers to their percentages of the sum of the list values (e.g., 1 2 2 -> 0.2 0.4 0.4), you can write the function

func =: %+/

but just writing %+/ numbers where numbers is a list of numbers doesn't work -- why is this? Why do you need to put parentheses around the function composition?


Solution

  • J evaluates every expression from right to left, unless it sees a parenthesis (in which case it evaluates the expression in the parenthesis - right to left - and then continues leftwards).

    Examples:

    1 - 2 - 3 - 4 - 5
    3                  NB. because it's: 1 - (2 - (3 - (4 - 5)))
    
    %+/ 1 2 3
    0.166667           NB. because it's: % (+/ 1 2 3) -> % (1 + (2 + 3))
    
    (%+)/ 1 2 3
    1.5                NB. because it's: 1 (%+) (2 (%+) 3)
    

    Also note that adverbs don't split. i.e. / can't stand on its own.