Yep, it uses a stack (not really a true stack though, its actually a linked list with pushing and popping from the front). Your expression gave me 172 with the program I wrote. I checked with the infix version in a 'usual' calculator, and it's right.Kojack wrote:Knowing absolutely no haskell... is that actually handling rpn or just number number operation triplets? Because rpn can look like: 4 7 2 8 9 + 2 * + + *
which is 4*(7+2+(8+9)*2)
The interesting part here is the (x:y:xs) which 'deconstructs' the list. x and y get assigned to the first and second elements, xs is the list of the rest of the elements. We then assign the stack back to x * y : xs which puts the result of the operation and the rest. One way to construct list is with 'element : list'. This adds element 'element' to the front of the list 'list'. Using this construct as an lvalue 'matches' the pattern and thats how the deconstruction works.
'foldl' is a function that takes a function, an initial value, and a list. It applies the given function to the list and accumulates the result (for the first element, the initial value is taken). In this case, the list we pass is the list of space-seperated words in the expression, and the function is our pattern matching one. 0 is the initial value. Then the patterns are matched (pattern ma'tching is a 'usual' thing, its how parameters to a function are assigned), and the appropriate operation is carried out, and the accumulated value is set to x (op) y : xs (where (op) is the appropriate operator).
Haskell allows you to do some pretty cool things because of its laziness. You can print infinite lists. Because its lazy, they don't get evaluated yet, and it evaluates them as they're being printed. This is an awesome example, it gives an infinite list of fibonacci numbers:-
Code: Select all
fib = 0 : 1 : zipWith (+) fib (tail fib)Code: Select all
0 : 1 : zipWith (+) (0 : 1 : ...) (1 : ...)
0 : 1 : (0 + 1) : zipWith (+) (1 : 1 : ...) (1 : ...)
0 : 1 : 1 : (1 + 1) : zipWith (+) (1 : 2 : ...) (2 : ...)
0 : 1 : 1 : 2 : (1 + 2) : zipWith (+) (2 : 3 : ...) (3 : ...)I can feel the brain expansion effect kick-in. Haskell really makes you think differently.



