2009-09-03 116 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 
) 

我最近的嘗試是一個很好的交易近距離獲取價值錯誤。仍然不知道爲什麼它失敗了,但我很快就會得到它。我想通了,我忘了所需要做的。在條件添加之後修復了所有內容。