Reputation: 21
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
Upvotes: 2
Views: 300
Reputation: 7616
Map is doubly built into APL:
map
:double←×∘2 double 1 2 3 4 5 6
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)
Upvotes: 5