Wednesday, February 28, 2024
Google search engine
HomeUncategorizedThinking in an Array Language

Thinking in an Array Language

{“payload”:{“allShortcutsEnabled”:false,”fileTree”:{“”:{“items”:[{“name”:”.github”,”path”:”.github”,”contentType”:”directory”},{“name”:”code”,”path”:”code”,”contentType”:”directory”},{“name”:”.gitignore”,”path”:”.gitignore”,”contentType”:”file”},{“name”:”00-preface.md”,”path”:”00-preface.md”,”contentType”:”file”},{“name”:”01-intro.md”,”path”:”01-intro.md”,”contentType”:”file”},{“name”:”02-working-with-arrays.md”,”path”:”02-working-with-arrays.md”,”contentType”:”file”},{“name”:”03-functions-and-variables.md”,”path”:”03-functions-and-variables.md”,”contentType”:”file”},{“name”:”04-index-apply.md”,”path”:”04-index-apply.md”,”contentType”:”file”},{“name”:”05-adverbs.md”,”path”:”05-adverbs.md”,”contentType”:”file”},{“name”:”06-numbers-and-logic.md”,”path”:”06-numbers-and-logic.md”,”contentType”:”file”},{“name”:”07-more-adverbs.md”,”path”:”07-more-adverbs.md”,”contentType”:”file”},{“name”:”08-dicts-table-strings.md”,”path”:”08-dicts-table-strings.md”,”contentType”:”file”},{“name”:”09-special-forms.md”,”path”:”09-special-forms.md”,”contentType”:”file”},{“name”:”10-io.md”,”path”:”10-io.md”,”contentType”:”file”},{“name”:”11-debug-errors.md”,”path”:”11-debug-errors.md”,”contentType”:”file”},{“name”:”12-thinking-in-k.md”,”path”:”12-thinking-in-k.md”,”contentType”:”file”},{“name”:”13-a-prelude.md”,”path”:”13-a-prelude.md”,”contentType”:”file”},{“name”:”14-sudoku.md”,”path”:”14-sudoku.md”,”contentType”:”file”},{“name”:”15-embedding-online.md”,”path”:”15-embedding-online.md”,”contentType”:”file”},{“name”:”readme.md”,”path”:”readme.md”,”contentType”:”file”}],”totalCount”:20}},”fileTreeProcessingTime”:3.224424,”foldersToFetch”:[],”reducedMotionEnabled”:null,”repo”:{“id”:441726628,”defaultBranch”:”main”,”name”:”ngn-k-tutorial”,”ownerLogin”:”razetime”,”currentUserCanPush”:false,”isFork”:false,”isEmpty”:false,”createdAt”:”2021-12-25T17:27:17.000Z”,”ownerAvatar”:”https://avatars.githubusercontent.com/u/11015319?v=4″,”public”:true,”private”:false,”isOrgOwned”:false},”symbolsExpanded”:false,”treeExpanded”:true,”refInfo”:{“name”:”main”,”listCacheKey”:”v0:1654249799.0786948″,”canEdit”:false,”refType”:”branch”,”currentOid”:”f8889c420f8597649493de0adbc37e9ebef9af49″},”path”:”12-thinking-in-k.md”,”currentUser”:null,”blob”:{“rawLines”:null,”stylingDirectives”:null,”csv”:null,”csvError”:null,”dependabotInfo”:{“showConfigurationBanner”:false,”configFilePath”:null,”networkDependabotPath”:”/razetime/ngn-k-tutorial/network/updates”,”dismissConfigurationNoticePath”:”/settings/dismiss-notice/dependabot_configuration_notice”,”configurationNoticeDismissed”:null,”repoAlertsPath”:”/razetime/ngn-k-tutorial/security/dependabot”,”repoSecurityAndAnalysisPath”:”/razetime/ngn-k-tutorial/settings/security_analysis”,”repoOwnerIsOrg”:false,”currentUserCanAdminRepo”:false},”displayName”:”12-thinking-in-k.md”,”displayUrl”:”https://github.com/razetime/ngn-k-tutorial/blob/main/12-thinking-in-k.md?raw=true”,”headerInfo”:{“blobSize”:”5.36 KB”,”deleteInfo”:{“deleteTooltip”:”You must be signed in to make or propose changes”},”editInfo”:{“editTooltip”:”You must be signed in to make or propose changes”},”ghDesktopPath”:”https://desktop.github.com”,”gitLfsPath”:null,”onBranch”:true,”shortPath”:”23c7bc5″,”siteNavLoginPath”:”/login?return_to=https%3A%2F%2Fgithub.com%2Frazetime%2Fngn-k-tutorial%2Fblob%2Fmain%2F12-thinking-in-k.md”,”isCSV”:false,”isRichtext”:true,”toc”:[{“level”:1,”text”:”Thinking in an array language”,”anchor”:”thinking-in-an-array-language”,”htmlText”:”Thinking in an array language”}],”lineInfo”:{“truncatedLoc”:”150″,”truncatedSloc”:”121″},”mode”:”file”},”image”:false,”isCodeownersFile”:null,”isPlain”:false,”isValidLegacyIssueTemplate”:false,”issueTemplateHelpUrl”:”https://docs.github.com/articles/about-issue-and-pull-request-templates”,”issueTemplate”:null,”discussionTemplate”:null,”language”:”Markdown”,”languageID”:222,”large”:false,”loggedIn”:false,”newDiscussionPath”:”/razetime/ngn-k-tutorial/discussions/new”,”newIssuePath”:”/razetime/ngn-k-tutorial/issues/new”,”planSupportInfo”:{“repoIsFork”:null,”repoOwnedByCurrentUser”:null,”requestFullPath”:”/razetime/ngn-k-tutorial/blob/main/12-thinking-in-k.md”,”showFreeOrgGatedFeatureMessage”:null,”showPlanSupportBanner”:null,”upgradeDataAttributes”:null,”upgradePath”:null},”publishBannersInfo”:{“dismissActionNoticePath”:”/settings/dismiss-notice/publish_action_from_dockerfile”,”dismissStackNoticePath”:”/settings/dismiss-notice/publish_stack_from_file”,”releasePath”:”/razetime/ngn-k-tutorial/releases/new?marketplace=true”,”showPublishActionBanner”:false,”showPublishStackBanner”:false},”rawBlobUrl”:”https://github.com/razetime/ngn-k-tutorial/raw/main/12-thinking-in-k.md”,”renderImageOrRaw”:false,”richText”:”

n

You can view the full source code for this chapter at GitHub.

n

Since you are now properly acquainted with K, let’s do some programming.nMost K programming happens through the REPL, because it is very useful to iterate upon previous code. ngn/k with rlwrap has history with the up/down arrow keys, and that should be more than enough to begin developing bigger programs in K. Functions are tested in the REPL, and then moved to actual code. Note that ngn/k’s prettyprinting always returns valid k data, and you can precompute some things beforehand to speed up your program.

n

A K script is always executed like it was typed in the repl, that is: Each line is executed, and its return value is printed unless it ends with a semicolon. A script also allows multiline definitions, which are convenient for readability. Oftentimes, you may save your work in a script, and want to use it in a repl. In order to use your stored data and functions, just do \l file.k in the repl, and your file will be executed, and its data will be loaded. You can load a file into the REPL more than once, overwriting older data. The repl help accessed with \ lists more useful commands as well.

n

K programming (and array programming in general), is a continuous process of simplifying your patterns. A big, unwieldy pattern has one or more ways to condense to a smaller, more declarative, easy to read pattern. This is discussed in a lot of detail in Patterns and Anti-patterns in APL: Escaping the Beginner’s Plateau – Aaron Hsu – Dyalog ’17, if you’d like to understand it better.

n

A common problem most people have in K is the need to translate a common, well known algorithm to K, usually taken from a programming website like geeksforgeeks, or a Wikipedia article. Let us take an example: Matrix Multiplication.

n

From this wikipedia article, the iterative algorithm for matrix multiplication is as follows:

n

Input: matrices A and BnLet C be a new matrix of the appropriate sizenFor i from 1 to n:n  For j from 1 to p:n    Let sum = 0n    For k from 1 to m:n      Set sum ← sum + Aik × Bkjn  Set Cij ← sumnReturn Cn

n

If you want, you can try translating this to K. A direct translation would be:

n

matmul: {n  A::xn  B::yn  n::#An  m::#*An  p::#*Bn  C::(n;p)#0n  i::0n  j::0n  k::0n  sum::0n  {n    i::xn    {n      j::xn      sum::0n      {n        k::xn        sum::sum+A[i;k]*B[k;j] n      }'!mn      C[i;j]::sumn    }'!pn  }'!nn  C}n

n

This is the worst K code I’ve ever written, because we are trying to write K like an imperative language, and K doesn’t work well with that design. The main problems are:

n

    n

  • Many, many globals are assigned
  • n

  • multiple nested loops
  • n

  • lots of modification
  • n

n

Luckily, there are a lot of things we can simplify here, and we can address these problems one by one.

n

Let us begin at the innermost loop:

n

sum::0n{n  k::xn  sum::sum+A[i;k]*B[k;j] n}'!mnC[i;j]::sumn

n

The first and simplest fix we can make is summing using a fold (/).

n

C[i;j]::+/{n  k::xn  A[i;k]*B[k;j] n}'!mn

n

One global down, 9 more to go.

n

The next global we can remove is C. Since ' (each) returns an array, C doesn’t need to be modified. We can simply return the value of the nested loop.

n

  {n    i::xn    {n      j::xn      +/{n        k::xn        A[i;k]*B[k;j] }'!m }'!p }'!n}n

n

Now, we have three loops with no modification, which makes our job much easier. The main variables to look at now are i, j, and k.

n

    n

  • i indexes each row of A.
  • n

  • j indexes each column of B.
  • n

  • k indexes each column of A and row of B.
  • n

n

Basically, k is responsible for pairing each row of A with each column of B, which are then multiplied. Hence, we can eliminate the middle man here, and directly match them without k. This also eliminates one loop, and removes the need for m.

n

{n  j::xn  +/A[i]*B[;j] }'!p }'!n}n

n

Next, to remove j, we need to take each column of B and pair it with A[i]. To do this, we transpose B and pair each element with eachright (/:).

n

matmul: {n  A::xn  B::yn  n::#An  i::0n  {n    i::xn      A[i]{+/x*y}/:+B}'!n }n

n

In order to remove i, we do a similar thing: Use eachleft to pair each row of A with each column of B.

n

matmul: {n  A::xn  B::yn  A{+/x*y}/:\:+B }n

n

We need no more globals!

n

matmul: {x{+/x*y}/:\:+y}n

n

Now that is matrix multiplication in K. This is the most direct algorithmic conversion of matrix multiplication. Now we will look at ways to shorten it, and remove more loops.

n

+ (transpose) is costly, and we can remove it. What we are currently doing is naive. Instead of multiplying each row of x with each column of y, we can conform each row of B to the whole of A, doing the same thing implicitly.

nn

Now, we have a function which can be easily made tacit. With the rules from Chapter 3, we get our final result:

nn

A matrix multiplication function you can be proud of. This process may seem like it has a lot of steps, but condensing code will become much easier and intuitive as you practice your skill in K.

n

Matrix multiplication is a simple procedure which works well with K’s array support. We will be seeing more algorithms that don’t play well with K, and how to handle them in future chapters.

n

“,”renderedFileInfo”:null,”shortPath”:null,”tabSize”:8,”topBannersInfo”:{“overridingGlobalFundingFile”:false,”globalPreferredFundingPath”:null,”repoOwner”:”razetime”,”repoName”:”ngn-k-tutorial”,”showInvalidCitationWarning”:false,”citationHelpUrl”:”https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/creating-a-repository-on-github/about-citation-files”,”showDependabotConfigurationBanner”:false,”actionsOnboardingTip”:null},”truncated”:false,”viewable”:true,”workflowRedirectUrl”:null,”symbols”:{“timed_out”:false,”not_analyzed”:false,”symbols”:[{“name”:”Thinking in an array language”,”kind”:”section_1″,”ident_start”:2,”ident_end”:31,”extent_start”:0,”extent_end”:5488,”fully_qualified_name”:”Thinking in an array language”,”ident_utf16″:{“start”:{“line_number”:0,”utf16_col”:2},”end”:{“line_number”:0,”utf16_col”:31}},”extent_utf16″:{“start”:{“line_number”:0,”utf16_col”:0},”end”:{“line_number”:150,”utf16_col”:0}}}]}},”copilotInfo”:null,”copilotAccessAllowed”:false,”csrf_tokens”:{“/razetime/ngn-k-tutorial/branches”:{“post”:”U_OqpWqnLQaQzDnD4RbgoXO-byw8SF1viBM56jrQ8pLqNYyJsyHW3vMx0Zrh2GyNxg_NuPwdVVmzmCoZwEuquQ”},”/repos/preferences”:{“post”:”0EMknYhwP1htCcqAqL_sqhzY1P33P9_0j9s_6k2JAARCze_xwq4q7Yb6MLVlJdPcOEYQMX2gKUSPxy70tPWrtQ”}}},”title”:”ngn-k-tutorial/12-thinking-in-k.md at main · razetime/ngn-k-tutorial”}

Read More

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments