Arithmetic mean forwards vs backwards? - j

I'm familiar with this way of doing an arithmetic mean in J:
+/ % #
But it's also shown here as
# %~ +/
Are these two versions interchangeable, and if not when should I use one versus the other?

Dyadic ~ reverses the arguments of a verb. x f~ y is equivalent to y f x. You use ~ when you, um, want to reverse the arguments of a verb.
One of its most common uses is for forks and hooks composition. For example, because y f (g y) is (f g) y you can use ((f~) g) y when you need (g y) f y.

In the reverse mean example I don't really see a reason that one way would be more effective than the other (V V V form of fork), but because forks in J can be non-symmetric (in the N V V form) I can see some reasons that reversing the middle tine of the fork would be an advantage. Take for example:
(5 # $) 1 2 3 NB. (N V V) form
3 3 3 3 3
(5 #~ $) 1 2 3 NB. (N V~ V) becomes effectively (V V N)
5 5 5
($ # 5) 1 2 3 NB. (V V N) is a syntax error
|syntax error
| ($#5)1 2 3

Dyadic ~ is the "Passive" adverb, which swaps the left and right arguments. Thus x f~ y is the same as y f x. +/ % # and # %~ +/ are equivalent. 2 % 5 gives you 0.4, but 2 %~ 5 gives 2.5.
Among the places this can be handy is checking the results of a line you are working with. While you would presumably be testing something more complicated, you can check yourself by repeating your last line and just adding to the left without rearranging anything or adding parentheses.
string =. 'J is beyond awesome.'
'e' = string
0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 1 0
string #~ 'e' = string
eee
The monadic ~ is the "Reflex" adverb, which causes the modified verb to operate as a dyad, duplicating the single argument for both left and right. While this is another shortcut to arranging your arguments, it is quite different from the dyadic ~. *~ 4 is 16, because you are multiplying y by itself (y * y).

Related

Number of arguments of composition in haskell

Recently I have been learning about compositions in haskell and am now a bit confused concerning this example.
(const . min) 3 0 4
As a result I get 3, so internally it must be computed like:
const (min 3) 0 4
But I thought since min takes two arguments, it should look like this:
const (min 3 0) 4
So apparently the composition only takes this one argument, in this case 3, instead of all the arguments for min like I expected it to. Does that mean compositions only take one argument per default or what am I not getting here?
You can answer your question by manually evaluating the initial expression.
(const . min) 3 0 4
⇒ (\x -> const (min x)) 3 0 4 * defn of (.)
⇒ (const (min 3)) 0 4 * function application
⇒ ((\x y -> x) (min 3)) 0 4 * defn of const
⇒ (\y -> min 3) 0 4 * function application
⇒ (min 3) 4 * function application
⇒ 3 * because 3 is less than 4
It is worth noting that function application is left-associative, so, f x y means the same as (f x) y.
It is also worth noting that \x y -> z means the same as \x -> \y -> z.

Write `4 : '$ x (<") y'` tacitly

How can I write the frame function tacitly? (From "Learning J" Ch 7)
I'm using the f x g y = x f#:g y composition scheme from Ch 8 , but it's not working. My guess is because <" has no natural rank?
x=.1
y=.i.2 3 4
f=.$
g=.<"
frame_e=.4 :'f x g y'
frame_t=.f#:g
x frame_e y NB. -> 2 3, which is the x-frame of y
x frame_t y NB. -> domain error
NB. No natural rank
g b.0 NB. -> syntax error
0 g b.0 NB. -> 0 0 0
I confirmed the pattern works as I expected with other functions.
x=.1
y=.i.2 3 4
f=.+/
g=.*
f x g y NB. -> equiv of 12+2*i.3 4
x f#:g y NB. -> same
Tacitly, I would do it using
framet=. {. $
2 framet i. 2 3 4
2 3
but that does not really get to the root of your question, does it?
The issue is really the way that g is defined:
g=.<"
This does not make g a verb, but an adverb. It does use the x in the explicit definition to create a verb, but it needs to do this before it uses that verb to evaluate y. As far as I know, J does not allow you to stage these processes. As you have seen the pattern does work when f and g are actually verbs.
I find tacit programming elegant, but it can be slower at some things and there are areas where it is limited.
I am hoping that someone can provide a better answer, so that I may learn as well.

Argument Usage: ti=.{.(*i.)}

I'm trying to get my head around J. In the easy-j.pdf (available here; page 19) introduction there is this hook:
ti=.{.(*i.)}. NB. ti=times index generator
ti 2 5 NB. Usage
I understand the previous term: 2(*i.)5 NB. 2 times 0 1 2 3 4
I can understand/imagine that }. takes the last element from the argument-list (above 2 5) to create (*i.)5. But what makes it clear/obvious that somehow the argument-list is also passed to {. to retrieve the 2 (in my current understanding the argument is already used by }.)?
I hope this question is understandable to J experts.
ti is actually a monadic fork with three tines that are all verbs. The way that this is executed is that the two outside tines {. and }. are executed on the argument 2 5 and the result is fed as left and the right arguments of the middle tine (* i.), which is itself a hook.
In J fork operations are often symbolized with f, g and h standing for verbs and x and y representing left and right arguments and forks are evaluated like this:
(f h g) y <-> (f y) h (g y) NB. <-> is a meta symbol for equivalency - not J symbols
In this case f y is {. 2 5 and g y is }. 2 5
{. 2 5
2
}. 2 5
5
The middle tine of a fork is always dyadic because it is fed from the two outside tines and the construct for the dyadic hook (* i.) in the centre is
x (f g) y <-> x f (g y)
2 (* i.) 5 NB. 2 * (i. 5)
0 2 4 6 8

Pascal Triangle in Haskell

I'm new to Haskell and I really need some help!
I have to write a program that includes a recursive function to produce a list of binomial coefficients for the power n=12 using the Pascal's triangle technique.
I have some ideas in my head but because I'm just getting started I have no idea how to implement this to haskell?!
Could someone please help me out??
first row: (a+b)^0 = 1
second row: (a+b)^1 = 1a+1b
third row: (a+b)^2 = 1a^2+2ab+1b^2
and so on...this is my main idea. But I cant even try this out because I have no idea how I put this in Haskell..getting errors all the time
Start by assigning an index to each element in the triangle:
| 0 1 2 3 4 5 6
--+--------------------------
0 | 1
1 | 1 1
2 | 1 2 1
3 | 1 3 3 1
4 | 1 4 6 4 1
5 | 1 5 10 10 5 1
6 | 1 6 15 20 15 6 1
Here I've simply put the triangle on its side so that we can number them. So here I'd say that the element at (6, 4) is 15, whereas (4, 6) doesn't exist. Now focus on writing a function
pascal :: Integer -> Integer -> Integer
pascal x y = ???
Such that you can generate this version of the triangle. You can start by writing
pascal x y
| x == 0 = 1
| x == y = 1
| x < y = error "Not a valid coordinate for Pascal's triangle."
| otherwise = pascal ? ? + pascal ? ?
Note that here, instead of figuring out which elements should be added together by diagonals, you can do it via rectangular coordinates. Here, you'll note that y is which row in the triangle you're on and x is the position of the element in that row. All you need to do is figure out what goes in place of the ?s.
Once you get that working, I've got a one-liner for this triangle that is more efficient and can generate the entire triangle all at once while still using recursion:
import Data.List (scanl1)
pascals :: [[Integer]]
pascals = repeat 1 : map (scanl1 (+)) pascals
Don't try turning this solution in to your professor, it's not what they're looking for and it would make it pretty obvious someone gave you this solution if you've only been doing Haskell for a week. However, it really shows how powerful Haskell can be for this sort of problem. I would show how to index pascals to get a given (n, k) value, but doing so would also give you too many hints for solving the naive recursion.
Since there's been some confusion, the reason why I gave this solution is to draw a parallel between it and the often shown lazy implementation for the Fibonacci sequence:
fibs = 1 : 1 : zipWith (+) fibs (tail fibs)
Compared to
fib 0 = 1
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)
This definition generates an infinite list of all the Fibonacci numbers, and does so quite efficiently (from the point of view of the CPU, RAM is a different story). It encodes in its first 2 elements the base case, then a recursive expression that can calculate the rest. For the Fibonaccis, you need 2 values to start you off, but for Pascal's triangle, you only need one value, that value just happens to be an infinite list. There is an easy to see pattern going across the columns in the grid I posted above, the scanl1 (+) function just takes advantage of this pattern and allows us to generate it very easily, but this is generating the diagonals of the triangle rather than the rows. To get the rows, you can index this list, or you can do some fancy tricks with take, drop, and other such functions, but that's an exercise for another day.
Start out with the triangle itself:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
...
You should notice that to write down the next row, you must apply this rule: sum the previous rows' adjacent elements, using a 0 for the lonely edge elements. Visually:
0 1 0
\+/ \+/
0 1 1 0
\+/ \+/ \+/
0 1 2 1 0
\+/ \+/ \+/ \+/
1 3 3 1
...
Operationally, that looks like this:
For row 0:
[1] (it's a given; i.e. base case)
For row 1:
[0, 1] <- row 0 with a zero prepended ([0] ++ row 0)
+ +
[1, 0] <- row 0 with a zero appended (row 0 ++ [0])
= =
[1, 1] <- element-wise addition
For row 2:
[0, 1, 1]
+ + +
[1, 1, 0]
= = =
[1, 2, 1]
Generally, for row N:
element-wise addition of:
[0] ++ row(N-1)
row(N-1) ++ [0]
Remember that element-wise addition of lists in Haskell is zipWith (+).
Thus we arrive at the following Haskell definition:
pascal 0 = [1]
pascal n = zipWith (+) ([0] ++ pascal (n-1)) (pascal (n-1) ++ [0])
Or in a fashion similar to the famous "lazy fibs":
pascals = [1] : map (\xs -> zipWith (+) ([0] ++ xs) (xs ++ [0])) pascals
Another possible solution (more suitable for beginners in my opinion):
pascal :: Integer -> [Integer]
pascal 0 = [1]
pascal 1 = [1, 1]
pascal n = let p = pascal (n - 1)
in [1] ++ pascalStep p ++ [1]
pascalStep :: [Integer] -> [Integer]
pascalStep [] = []
pascalStep [_] = []
pascalStep (x:y:xs) = x + y : pascalStep (y : xs)
Using let to avoid more space usage.
pascal is calling recursively to find all previous rows, using them to get the next row, until getting to the desired row.
Output:
*Main> pascal 3
[1,3,3,1]
*Main> pascal 4
[1,4,6,4,1]
*Main> pascal 5
[1,5,10,10,5,1]
Start with the base case.
pascal 0 0 = 1
Then handle the edge cases
pascal n 0 = 1
pascal n r | n == r = 1
Now expand with the recursive step
pascal n r = pascal (n - 1) (r - 1) + pascal (n - 1) r
If you want the list for a specific row, write a wrapper
binom n = map (pascal n) [0..n]
Figuring out the types shouldn't be hard
pascal :: Integral a => a -> a -> a
binom :: Integral a => a -> [a]
I'm on my phone so please excuse the mistakes, but you can use Haskell's lazy evaluation in a really cool way here.
pascals :: [[Int]]
pascals = [1]:map (\r -> zipWith (+) (0:r) (r++[0])) pascals
Which you could make point free with a fork but it's rather esoteric.
pascals :: [[Int]]
pascals = [1]:map ((zipWith (+) -<) (0:) (++[0])) pascals
But I personally really like this code, and thinks it's worth being readable-
pascals :: [[Int]]
pascals = [1]:map next pascals
where next = (zipWith (+) -<) (0:) (++[0])
But combinators like that can get a bit confusing, no matter how much I like point free programming.

How to define an infinite 2D array recursively in Haskell?

I'm new to Haskell, and I like its graceful grammar. But I haven't found a suitable way to define an infinite 2D array -- for example, the Pascal Triangle:
1 1 1 1 1 ...
1 2 3 4 5 ...
1 3 6 10 15 ...
1 4 10 20 35 ...
1 5 15 35 70 ...
...
I know how to define a simple function:
pascal :: Int -> Int -> Int
pascal 1 _ = 1
pascal _ 1 = 1
pascal x y = (pascal (x - 1) y) + (pascal x (y - 1))
Since Haskell do not memorize function values, a call to pascal 20 20 will take a long time. How could I define a fast version (like an infinite 2D array)?
You can create the pascal triangle as an infinite, lazy, nested list
pascal :: [[Integer]]
pascal = repeat 1 : map (scanl1 (+)) pascal
The above definition is a bit terse but what it essentially means is just that each row is an accumulating sum of the previous row, starting from repeat 1 i.e. an infinite list of ones. This has the advantage that we can calculate each value in the triangle directly without doing any O(n) indexing.
Now you can index the list to find the value you need, e.g.
> pascal !! 19 !! 19
35345263800
The list will only get partially evaluated for the values you need.
You can also easily output a range of values:
> putStrLn $ unlines $ take 5 $ map (unwords . map show . take 5) $ pascal
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70
Another option is to use your original function but memoize it using one of the various memorization libraries available. For example, using data-memocombinators:
import Data.MemoCombinators
pascal :: Integer -> Integer -> Integer
pascal = memo2 integral integral pascal'
pascal' :: Integer -> Integer -> Integer
pascal' 1 _ = 1
pascal' _ 1 = 1
pascal' x y = (pascal (x - 1) y) + (pascal x (y - 1))
The obvious choice for an infinite 2D "array" would be a nested list, i.e. an infinite list of infinite lists. It might thus be
pascal' :: [[Integer]]
pascal' = repeat 1 : [ 1 : [ pascalGen x y | y<-[1..] ] | x<-[1..] ]
where pascalGen x y = pascal' !! (x-1) !! y + pascal' !! x !! (y - 1)
This now has the function calls memoised. It's still not optimal because of list O (n) access, but not that bad either.

Resources