简体   繁体   中英

Implement Map function in APL Language

I have created the map function using Scheme , but I want to implement it in APL .

(define (map func lstt)
 (cond
 ((null? lst) '())
 (else (cons (func (car lst))
 (map func (cdr lst))))
 )
)

The map function takes two arguments : a function: func (like double: *2 ) and list of integers: lst

Calling map with double (*2) and list (1 2 3) will result in list (2 4 6)

Any help to implement it in APL

Map is doubly built into APL:

  1. Every arithmetic function have an implicit map :
     double←×∘2 double 1 2 3 4 5 6
  2. A general purpose map is also built in, namely ¨ :
     reverse←⌽ reverse 'abc' 'def' 'ghi' ┌───┬───┬───┐ │ghi│def│abc│ └───┴───┴───┘ reverse¨'abc' 'def' 'ghi' ┌───┬───┬───┐ │cba│fed│ihg│ └───┴───┴───┘ 

That said, you can define map recursively as in your example code. For simplicity, let's restrict the domain to lists:

map←{0=≢⍵:⍵ ⋄ (⊂⍺⍺⊃⍵),∇1↓⍵}
reverse map 'abc' 'def' 'ghi'
┌───┬───┬───┐
│cba│fed│ihg│
└───┴───┴───┘
This is how it works:

map←{⍺⍺} defines map to be a monadic operator

0=≢⍵: if the argument has no elements (zero equals the tally of the argument)

return the argument

else

(⊂⍺⍺⊃⍵) open up the first element, apply the function and close it again

,∇1↓⍵ concatenated with recursion the rest of the argument (one element dropped from the argument)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM