Fibonacci numbers in WebAssembly doesn't compile - fibonacci

I've tried to make recursive and array-based Fibonacci sequence in WebAssembly, to see which one is faster and therefore to determine whether WebAssembly supports tail recursion optimisation (because I can't find any data about it).
(module
(memory 1)
(func $recursive_fib (param $n i32) (result i32)
(if (i32.lt_s (local.get $n) (i32.const 2))
(return (local.get $n))
)
(local.get $n)
(i32.const 1)
(i32.sub)
(call $recursive_fib)
(local.get $n)
(i32.const 2)
(i32.sub)
(call $recursive_fib)
(i32.add)
)
(export "recursive_fib" (func $recursive_fib))
(func $array_fib (param $n i32) (result i32) (local $i i32)
(i32.const 0)
(i32.store (i32.const 0))
(i32.const 1)
(i32.store (i32.const 4))
(i32.const 2)
(local.set $i)
(loop
(br_if 1 (i32.gt_s (local.get $i) (local.get $n)))
(local.get $i)
(i32.const 1)
(i32.sub)
(i32.const 4)
(i32.mul)
(i32.load)
(local.get $i)
(i32.const 2)
(i32.sub)
(i32.const 4)
(i32.mul)
(i32.load)
(i32.add)
(i32.store (i32.mul (i32.const 4) (local.get $i)))
(local.get $i)
(i32.const 1)
(i32.add)
(local.set $i)
(br 0)
)
(local.get $n)
(i32.const 4)
(i32.mul)
(i32.load)
)
(export "array_fib" (func $array_fib))
)
However, when I try to compile it, I get this error:
fibonacci.wat:26:14: error: type mismatch in br_if, expected [i32] but got []
(br_if 1 (i32.gt_s (local.get $i) (local.get $n)))
^^^^^
What am I doing wrong?

Solved it myself, here it goes:
(module
(memory 1)
(func $recursive_fib (param $n i32) (result i32)
(if (i32.lt_s (local.get $n) (i32.const 2))
(return (local.get $n))
)
(local.get $n)
(i32.const 1)
(i32.sub)
(call $recursive_fib)
(local.get $n)
(i32.const 2)
(i32.sub)
(call $recursive_fib)
(i32.add)
)
(export "recursive_fib" (func $recursive_fib))
(func $array_fib (param $n i32) (result i32) (local $i i32)
(i32.store (i32.const 0) (i32.const 0))
(i32.store (i32.const 4) (i32.const 1))
(local.set $i (i32.const 2))
(block (loop
(br_if 1 (i32.gt_s (local.get $i) (local.get $n)))
(i32.mul (i32.const 4) (local.get $i))
(local.get $i)
(i32.const 1)
(i32.sub)
(i32.const 4)
(i32.load (i32.mul))
(local.get $i)
(i32.const 2)
(i32.sub)
(i32.const 4)
(i32.load (i32.mul))
(i32.add)
(i32.store)
(local.set $i (i32.add (i32.const 1) (local.get $i)))
(br 0)
))
(local.get $n)
(i32.const 4)
(i32.load (i32.mul))
)
(export "array_fib" (func $array_fib))
)

Related

Implementing a C like program in racket using lex/yacc

I was looking at these two resources (https://github.com/racket/parser-tools/blob/master/parser-tools-lib/parser-tools/examples/calc.rkt and https://gist.github.com/gcr/1318240) and although I don't fully understand yet how the main calc function works I wondered if it's possible to extend this to work for a simple c like program just without functions? So it will lex, parse and evaluate ifs, whiles and print statements. So something like (define-empty-tokens op-tokens ( newline = OC CC (open-curly/closed-curly for block statements) DEL PRINT WHILE (WHILE exp S) S IF S1 S2 (IF exp S1 S2) OP CP + - * / || % or && == != >= <= > < EOF ))
Here is how I've extended it (the code of the first link) so far to also work with booleans:
So in calcl I added these two lines:
[ (:= 2 #\|) (token-||)]
[(:or "=" "+" "-" "*" "/" "%" "&&" "==" "!=" ">=" "<=" ">" "<") (string->symbol lexeme)]
And then later:
(define calcp
(parser
(start start)
(end newline EOF)
(tokens value-tokens op-tokens)
(error (lambda (a b c) (void)))
(precs (right =)
(left ||)
(left &&)
(left == !=)
(left <= >= < >)
(left - +)
(left * / %)
)
(grammar
(start [() #f]
[(error start) $2]
[(exp) $1])
(exp [(NUM) $1]
[(VAR) (hash-ref vars $1 (lambda () 0))]
[(VAR = exp) (begin (hash-set! vars $1 $3)
$3)]
[(exp || exp) (if (not(and (equal? $1 0) (equal? $3 0) )) 1 0) ]
[(exp && exp) (and $1 $3)]
[(exp == exp) (equal? $1 $3)]
[(exp != exp) (not(equal? $1 $3))]
[(exp < exp) (< $1 $3)]
[(exp > exp) (> $1 $3)]
[(exp >= exp) (>= $1 $3)]
[(exp <= exp) (<= $1 $3)]
[(exp + exp) (+ $1 $3)]
[(exp - exp) (- $1 $3)]
[(exp * exp) (* $1 $3)]
[(exp / exp) (/ $1 $3)]
[(exp % exp) (remainder $1 $3)]
[(OP exp CP) $2]))))
But I'm struggling to understand the above code as well as the below. I would lile to change it so that it also to works for ifs and whiles etc. if it's at all possible?
(define (calc ip)
(port-count-lines! ip)
(letrec ((one-line
(lambda ()
(let ((result (calcp (lambda () (calcl ip)) )))
(when result (printf "~a\n" result) (one-line))
)
) ))
(one-line))
)
Also, this guy seems to be relying on newlines to mark the end of a statement. i.e. you can't have more than 1 statement on one line. I want the program to recognise two statements on one line and evaluate them separately by somehow looking ahead and checking whether there's a new undeclared variable, special keyword or open/closed bracket etc.
Update:
I managed, with the below rules, to build in brag an AST for arith expressions but how do I get rid of all but the important parens so that I can evaluate it?
Eg: with input list: (list (token 'NUM 17) '+ (token 'NUM 1) '* (token 'NUM 3) '/ 'OP (token 'NUM 6) '- (token 'NUM 5) 'CP)
I'm getting back:
'(exp (((((factor 17)))) + (((((factor 1))) * ((factor 3))) / ((((((factor 6)))) - (((factor 5))))))))
Here are my rules:
exp : add
/add : add ('+' mul)+ | add ('-' mul)+ | mul
/mul : mul ('*' atom)+ | mul ('/' atom)+ | mul ('%' atom)+ | atom
/atom : /OP add /CP | factor
factor : NUM | ID
You cannot easily implement a language with conditionals and looping constructs using an evaluator based on immediate evaluation.
That should be clear at least for loops. If you have something like (using a super-simplified syntax):
repeat 3 { i = i + 1 }
If you evaluate during the parse, i = i + 1 will be evaluated exactly once, since the string is parsed exactly once. In order for it to be evaluated several times, the parser needs to convert i = i + 1 into something that can be evaluated several times when the repeat is evaluated.
This something is usually an Abstract Syntax Tree (AST), or possibly a list of virtual machine operations. With Scheme, you could also just turn the expression being parsed into a functional.
All of this is totally practical and not even particularly difficult, but you do need to be prepared to do some reading, both about parsing and about generating executables. For the latter, I highly recommend the classic Structure and Interpretation of Computer Programs (Abelson & Sussman).
Based on what I've seen here and here I managed to implement the lex and parse phase of an interpreter for a simple c-like program. It doesn't have functions in it but it has assignments, variables, conditionals, loops and print statements (As well as arithmetic, it also contains logical expressions.). I'm posting it below, in case others may find it useful (The whole thing including the evaluation phase and samples of input is here):
(require parser-tools/yacc //provides you with the lexer, the parser and the lexeme tools eg. string-> symbol, string->number etc - In general, with the ability to map the literals in the input
parser-tools/lex
(prefix-in : parser-tools/lex-sre))
(define-tokens value-tokens (NUM VAR ))
(define-empty-tokens op-tokens ( newline = OC CC DEL OP CP + - * / || % or && == != >= <= > < EOF PRINT WHILE IF ELSE ))
(define vars (make-hash)) ;to store the values in the variables
(define-lex-abbrevs
(lower-letter (:/ "a" "z"))
(upper-letter (:/ #\A #\Z))
(digit (:/ "0" "9")))
(define calcl ;lexer is mapping the literals to their tokens or values
(lexer
[(eof) 'EOF]
[(:or #\tab #\space #\return #\newline ) (calcl input-port)]
[ (:= 2 #\|) (token-||)]
[(:or "=" "+" "-" "*" "/" "%" "&&" "==" "!=" ">=" "<=" ">" "<") (string->symbol lexeme)]
["(" 'OP]
[")" 'CP]
["{" 'OC]
["}" 'CC]
[ "print" 'PRINT ]
[#\, 'DEL ]
[ "while" 'WHILE ]
[ "if" 'IF ]
[ "else" 'ELSE ]
[(:+ (:or lower-letter upper-letter)) (token-VAR (string->symbol lexeme))]
[(:+ digit) (token-NUM (string->number lexeme))]
))
(define calcp ;defines how to parse the program and how the program structure is made up (recursively)
(parser
(start start);refers to the block named 'start' below. Every parser has a start, end, tokens definition, optional error message when needed and operator precedence def.
(end EOF)
(tokens value-tokens op-tokens )
(error (λ(ok? name value) (if (boolean? value) (printf "Couldn't parse: ~a\n" name) (printf "Couldn't parse: ~a\n" value))))
(precs ;sets the precedence of the operators in relation to each other - that is, to which operand they bind stronger
(left DEL);from lowest to highest
(right =)
(left ||)
(left &&)
(left == !=)
(left <= >= < >)
(left - +)
(left * / %)
(right OP)
(left CP)
(right OC)
(left CC)
)
(grammar ;what is the grammar of my program?
(start
[() '()] ; returns empty list when it matches onto nothing
[(statements) `(,$1)]
[(statements start) `(,$1,$2)] ;we can have more than one statement - one example of the recursiveness
)
(statements /what type of major statements we might have
[(var = exp ) `(assign ,$1 ,$3)]
[(IF ifState) $2]
[(WHILE while) $2]
[(PRINT printVals) `(print ,$2)]
)
(ifState ; It's assumed that you cannot have an if inside an if unless it's within curly braces
[(OP exp CP statements) `(if ,$2 ,$4)] /combinations of different major statements
[(OP exp CP block) `(if ,$2 ,$4)]
[(OP exp CP block ELSE statements ) `(if ,$2 ,$4 ,$6)]
[(OP exp CP statements ELSE block ) `(if ,$2 ,$4 ,$6)]
[(OP exp CP statements ELSE statements ) `(if ,$2 ,$4 ,$6)]
[(OP exp CP block ELSE block ) `(if ,$2 ,$4 ,$6)]
)
(while
[(OP exp CP block) `(while ,$2, $4)]
)
(block
[(OC start CC) $2] ;we can statements or entire program wrapped into curly braces - a block
)
(var
[(VAR) $1]
)
(printVals
[(exp DEL printVals ) `(,$1 ,$3)]
[(exp) $1]
)
(exp [(NUM) $1] ; smallest (most reducible) chunk in an expression when the chunk is an integer
[(VAR) $1] ; smallest (most reducible) chunk in an expression when the chunk is a variable
[(exp || exp) `((lambda (a b) (or a b)) ,$1 ,$3) ]
[(exp && exp) `((lambda (a b) (and a b)) ,$1 ,$3)]
[(exp == exp) `(equal? ,$1 ,$3)]
[(exp != exp) `(not(equal? ,$1 ,$3))]
[(exp < exp) `(< ,$1 ,$3)]
[(exp > exp) `(> ,$1 ,$3)]
[(exp >= exp) `(>= ,$1 ,$3)]
[(exp <= exp) `(<= ,$1 ,$3)]
[(exp + exp) `(+ ,$1 ,$3)]
[(exp - exp) `(- ,$1 ,$3)]
[(exp * exp) `(* ,$1 ,$3)]
[(exp / exp) `(quotient ,$1 ,$3)]
[(exp % exp) `(modulo ,$1 ,$3)]
[(OP exp CP) $2]) ;when the expressions are wrapped parentheses
)
)
)
Procedure calls the parser passing it a lambda (that calls the lexer providing it with the input) which it will use to get values from the lexer, as many values at a time as it sees fit.
; i.e. according to what the parsing rules above, prescribe
(define (calceval ip)
(calcp (lambda () (calcl ip))))
To see the evaluator (unfortunately without much comments yet) see here

scheme - can someone explain this output to me?

With these defined functions:
(define (foldr op z ls)
(if (null? ls)
z
(op (car ls) (foldr op z (cdr ls)))))
(define (snoc x y) (cons y x))
and when i run this:
(foldr snoc '() (list 1 2 3))
I get this output:
=> (((() . 3) . 2) . 1)
What does this output mean? Can someone please explain it to me in detail?
I need to Draw this answer in terms of box and pointer notation in scheme.
Racket prints cons cells as "dotted pairs" if their cdr isn't a list.
Examples from DrRacket:
> (list 1 2)
'(1 2)
> '(1 . (2 . ()))
'(1 2)
> '(1 . 2)
'(1 . 2)
> (cons 1 2)
'(1 . 2)
> (cons 1 '())
'(1)
> (cons '() 1)
'(() . 1)
(foldr op z ls) takes ls and replaces nil with z and cons with op.
That is, if ls is (cons a (cons b (cons c nil))), then (foldr op z ls) is
(op a (op b (op c z)))
In your example, (foldr snoc '() (list 1 2 3)) is
(snoc 1 (snoc 2 (snoc 3 '())))
Working your way outwards from the innermost snoc,
(snoc 1 (snoc 2 (cons '() 3)))
(snoc 1 (cons (cons '() 3) 2))
(cons (cons (cons '() 3) 2) 1)
which prints (in DrRacket) as dotted pairs
'(((() . 3) . 2) . 1)
(Drawing a diagram left as an exercise.)

Parsing concrete syntax in Scheme

I wrote a procedure that gets a valid prefix list for subtraction (e.g, "(- 6 5)" for what we know as "6-5"). Here is my code:
(define parse-diff-list
(lambda (datum)
(cond
((number? datum) (const-exp datum)) ;; if datum is a number, return const-exp
((pair? datum) ;; if datum is a pair:
(let ((sym (car datum))) ;; let sym be the first of the pair
(cond
((eqv? sym '-) ;; if sym is minus:
(let ((lst1 (parse-diff-list (cdr datum)))) ;; parse second element of subtraction
(let ((lst2 (parse-diff-list (cdr lst1)))) ;; parse first element of subtraction
(cons (diff-exp (car lst1) (car lst2)) (cdr lst2))))) ;; "perform" the subtraction
((number? sym) ;; if sym is number:
(cons (const-exp sym) (cdr datum))) ;; return const-exp with the remainder of the list, yet to be processed
(else (eopl:error 'parse-diff-list "bad prefix-expression, expected - ~s" sym)))))
(eopl:error 'parse-diff-list "bad prefix-expression ~s" datum))))
(define parse-prefix
(lambda (lst)
(car (parse-diff-list lst))))
It works fine logically, but I don't understand the logic of the indentation in printing. For the input:
(parse-prefix '(- - 1 2 - 3 - 4 5))
It prints:
#(struct:diff-exp
#(struct:diff-exp #(struct:const-exp 1) #(struct:const-exp 2))
#(struct:diff-exp #(struct:const-exp 3) #(struct:diff-exp #(struct:const-exp 4) #(struct:const-exp 5)))
While I would want the following print style:
#(struct:diff-exp
#(struct:diff-exp
#(struct:const-exp 1)
#(struct:const-exp 2))
#(struct:diff-exp
#(struct:const-exp 3)
#(struct:diff-exp
#(struct:const-exp 4)
#(struct:const-exp 5)))
It's more than a petty question for me, as it does create indentations but I don't know how it does it.
Thanks a lot!
Take a look at racket/pretty the pretty printing library.
In particular note the parameter (pretty-print-columns) which
you can set like this:
`(pretty-print-columns 40)`
in order to avoid long lines.
http://docs.racket-lang.org/reference/pretty-print.html
(I am guessing you are using DrRacket based on the way the structures are printing)

Fibonacci numbers function in CLIPS

I can't create function for finding fibonacci numbers in CLIPS
i tryed
(deffunction fibo (?a )
( if (> ?a 0) then (+ fibo(- ?a 1) fibo(- ?a 2)) else (0)))
but it's doesn't work
Here is a function of calculating Fibonacci numbers recursively in CLIPS:
(deffunction fibo (?a)
(if (or (= ?a 0) (= ?a 1)) then
?a
else
(+ (fibo(- ?a 1)) (fibo(- ?a 2)))))
I don't understand, what your code does but there is error in it (you've missed brackets):
(deffunction fibo (?a )
( if (> ?a 0) then (+ ( fibo(- ?a 1) ) ( fibo(- ?a 2) )) else (0)))

Parse Error (x + 1) when Compiling in Haskell

I'm doing this assignment and I'm desperate to get this to work.
I know that this isn't the smartest way, and that it is not the most efficient way. I did this purely because I want to test how inefficient this code is.
transition_from_conductor :: Element_w_Coord Cell -> List_2D Cell -> Cell
transition_from_conductor element world = case num_of_heads_around_conductor (0, element) world of
1 -> Head
2 -> Head
_ -> Conductor
where
num_of_heads_around_conductor :: (Int, Element_w_Coord Cell) -> List_2D Cell -> Int
num_of_heads_around_conductor (i, (cell, (x, y))) ((w_cell, (w_x, w_y): rest)) = case rest of
[] -> i
_ -> case (w_cell, w_x, w_y) of
(Head, (x + 1), y) -> num_of_heads_around_conductor ((i + 1), (cell, (x, y))) (rest)
(Head, (x + 1), (y + 1)) -> num_of_heads_around_conductor ((i + 1), (cell, (x, y))) (rest)
(Head, (x + 1), (y - 1)) -> num_of_heads_around_conductor ((i + 1), (cell, (x, y))) (rest)
(Head, (x - 1), y) -> num_of_heads_around_conductor ((i + 1), (cell, (x, y))) (rest)
(Head, (x - 1), (y + 1)) -> num_of_heads_around_conductor ((i + 1), (cell, (x, y))) (rest)
(Head, (x - 1), (y - 1)) -> num_of_heads_around_conductor ((i + 1), (cell, (x, y))) (rest)
(Head, x, (y + 1)) -> num_of_heads_around_conductor ((i + 1), (cell, (x, y))) (rest)
(Head, x, (y - 1)) -> num_of_heads_around_conductor ((i + 1), (cell, (x, y))) (rest)
_ -> num_of_heads_around_conductor ( i , (cell, (x, y))) (rest)
If I try to run this in terminal, it gives me parse error (x + 1) on the
(Head, (x + 1), y) .....
What did I do wrong? and how do I fix it?
A few things...
type List_2D e = [Element_w_Coord e]
type Element_w_Coord e = (e, Coord)
type Coord = (X_Coord, Y_Coord)
type X_Coord = Integer
type Y_Coord = Integer
Thanks guys :D
Two things wrong here:
you can't use an arithmetic expression in a pattern
when you try to pattern match against x and y you intend to constrain those parts of the pattern to be equal to the existing x and y variables, but you instead create new variables x and y
I would use guards.
_ -> case (w_cell, w_x, w_y) of
(Head, x', y')
| x' == x + 1 && y' == y -> num_of_heads_around_conductor ((i + 1), (cell, (x, y))) (rest)
| x' == x + 1 && y' == y + 1 -> num_of_heads_around_conductor ((i + 1), (cell, (x, y))) (rest)
| x' == x + 1 && y' == y - 1 -> num_of_heads_around_conductor ((i + 1), (cell, (x, y))) (rest)
| x' == x - 1 && y' == y -> num_of_heads_around_conductor ((i + 1), (cell, (x, y))) (rest)
| x' == x - 1 && y' == y + 1 -> num_of_heads_around_conductor ((i + 1), (cell, (x, y))) (rest)
| x' == x - 1 && y' == y - 1 -> num_of_heads_around_conductor ((i + 1), (cell, (x, y))) (rest)
| x' == x && y' == y + 1 -> num_of_heads_around_conductor ((i + 1), (cell, (x, y))) (rest)
| x' == x && y' == y - 1 -> num_of_heads_around_conductor ((i + 1), (cell, (x, y))) (rest)
_ -> num_of_heads_around_conductor ( i , (cell, (x, y))) (rest)
And then simplify:
_ -> case (w_cell, w_x, w_y) of
(Head, x', y')
| x' == x + 1 && (y' == y || y' == y + 1 || y' == y - 1)
|| x' == x - 1 && (y' == y || y' == y + 1 || y' == y - 1)
|| x' == x && (y' == y + 1 || y' == y - 1)
-> num_of_heads_around_conductor ((i + 1), (cell, (x, y))) (rest)
_ -> num_of_heads_around_conductor ( i , (cell, (x, y))) (rest)
No doubt this can be simplified further.
What you have used is an "n + k" pattern, which has been removed from the language. You can no longer pattern match on integers using '+'. For the most part, pattern matches are restricted to constructors and literals.
To achieve the same result as your pattern match, I suggest:
(Head, x0, y) -> let x = x0 - 1 in ...
Notice that there is also more wrong with this code - the pattern matches are overlapped. For example: Even with n+k support, there is no case in which the pattern:
(Head, (x + 1), y)
Fails and the next pattern of:
(Head, (x + 1), (y + 1))
succeeds. In other words, you have many cases that can never be executed.

Resources