views:

116

answers:

2

I am attempting to learn J and the book I am using says this is the proper way to define a monadic function

function =: 3:0 
    function statements

so I followed this format and wrote the folding code. Can you tell me why this is throwing a syntax error when I try to call it with input but if I just call p it returns 3

h=:>:@i.@<.@-: :[: NB. gets all integers less than half of the input :[: forces error if used dyadicly
d=:(0&=|)~ h :[: NB. gets list where if one is set that index from h was a factor of the input y  :[: forces error if used dyadicly
p=: 3:0 NB. tells us p is a monadic function
   t =: d y 
   a =: i. 1
   while. 1<#t
      if. t~:0
         a =: a, #t
      end.
      t=: _1 }. t NB. found first mistake wrong bracket but fixing that doesn't fix it
   end.
   a*1
) 

NB. p gets a list of all integers that are factors of y
p 4
| syntax error
| p 4
p
3
NB. h and d run fine
h 4
    1 2
h 7
    1 2 3
d 7
    1 0 0
d 4
    1 1
A: 

I figured it out sort of I get a stack error instead of a syntax error with monad define instead of using 3:0. I still have to work out a few kinks but I'm making progress.

h =:>:@i.@<.@-:
d =:(0&=@|)~ h
p =: monad define
t =: d y 
a =: i.0
while. 1<#t do.
   if. {:t~:0 do.
      a=:a, #t
   end.
   t=: _1 }. t 
end.
a
)

my latest attempt is a good deal close getting a value error now. Still not sure why its failing but I'll get it soon. I figured it out I was forgetting the required do. after the conditionals adding them fixes everything.

faceless1_14
+1  A: 

Firstly, 3:0 parses like (3:) (0), i.e. the monad "3:" applied to the noun "0". That's not what you want; for definitions, you want to use the dyad ":", so you need to separate it from the 3 with a space.

Secondly, you should use =. instead of =: inside the definition, as t and a are local variables.

Several parts can be simplified:

d =: 0 = h | [             NB. does h y divide y
p =: d # h                 NB. select d y from h y

Same functionality as before, but clearer and faster.

ephemient
ah thank you I'm new to functional programming and very new to J it took me long enough to come up with something that did what I wanted I figured there was a faster way. The [ monad is the self monad right?
faceless1_14
J supports "function-level programming", but does not support "functional programming".In monadic context, `[` is an identity function (returns the argument). In dyadic context, it yields `x` and ignores `y` (returns the left argument). The definitions I give here utilize hooks and forks for combining verbs into new verbs.
ephemient