2009-09-03 160 views
1

我试图学习J和我使用的是书上说这是定义一个一元函数为什么这个J功能不能运行?

 
function =: 3:0 
    function statements 

所以我遵循了这一格式,并写了折叠代码的正确方法。你能告诉我这是为什么抛出一个语法错误,当我尝试输入称呼它,但如果我只是叫p将其返回3

h=:>:@[email protected]<[email protected]: :[: 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 
+0

J不是一种函数式编程语言。它是一种功能级编程语言。 (请参阅维基百科关于函数级编程的文章,以讨论其差异。) – 2009-11-28 02:44:03

回答

2

首先,3:0解析如(3:) (0),即适用于名词“0”的monad“3:”。这不是你想要的;对于定义,您想使用二元组“:”,因此需要用空格将其与3分开。

其次,你应该用=.代替=:的定义,因为ta是局部变量。

几个部分可以简化为:

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

相同的功能之前,但更清晰,速度更快。

+0

啊谢谢我对函数式编程不熟悉,对J非常新颖,花了我足够长的时间才想出了一些我想要的东西认为有一个更快的方法。 [monad是自我monad权利? – 2009-09-04 12:42:39

+0

J支持“功能级编程”,但不支持“功能编程”。 在monadic上下文中,'['是一个标识函数(返回参数)。在二元上下文中,它产生'x'并忽略'y'(返回左边的参数)。我在这里给出的定义利用钩子和叉把动词组合成新的动词。 – ephemient 2009-09-04 14:25:55

0

我想通了几分我得到一个堆栈错误而不是语法monad错误定义而不是使用3:0。我仍然需要解决一些问题,但我正在取得进展。

h =:>:@[email protected]<[email protected]: 
d =:(0&[email protected]|)~ 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 
) 

我最近的尝试是一个很好的交易近距离获取价值错误。仍然不知道为什么它失败了,但我很快就会得到它。我想通了,我忘了所需要做的。在条件添加之后修复了所有内容。