Creating function Trim-to(symbol list) in LISP - lisp

trim-to (symbol list)
Write a function named trim-to that takes a symbol and list as parameters. Return a new list
starting from the first occurrence of the input symbol in the input list. If there is no
occurrence of the symbol, return nil.
For example:
(trim-to ‘c ‘(a b c d e))
This should return the following list:
‘(c d e)
Not quite sure how to start here. If someone could walk me through the steps they take to construct this function I would be forever grateful!

You have a symbol and a list:
if the list is the empty list you have failed;
if the first element of the list is the symbol this is the list you want;
otherwise take the rest of the list – now you have a symbol and a list ...

Related

syntax for unsyntax in syntax-parse

can someone point me to how I can write this in syntax-parse/case?
[(list e ...) #`(list #,(f #'e) ...)]
basically I'd like each element in the list to be processed individually by f in unsyntax. I don't think the above is the right syntax?
You can use unsyntax-splicing (which can be abbreviated as #,#) to embed result of list returning expression as individual elements of outer list. Then you can use map procedure to apply f over all elements of list returned by (syntax->list #'(e ...)) expression. In the end it will look like this:
#`(list #,#(map f (syntax->list #'(e ...))))

kdb - resolving nested function when printing outer function body

I would like to print the function definition of any nested function when printing the definition of the outer function. Example:
g:{sin x}
f:{cos g x}
When I print f I get {cos g x} but I want to get {cos {sin x} x}
Thanks for the help
From what I am aware it is not possible to achieve that with in-build functions.
You can attempt to write your own function that does that but it will be a pain in the end. Something like this maybe:
q)m:string[v]!string value each v:value[f][3] except `
which creates a dictionary m :
q)m
,"g"| "{sin x}"
When given a function value returns a list containing (bytecode;parameters;locals(context;globals);constants[0];...;constants[n];definition)
However, if we pass a symbol to value it returns the value of that symbol (or function definition in this case).
You can then use ssr to replace the functions in f with the function definitions stored in your dictionary m.
q)ssr/[last value[f];key m;value m]
"{cos {sin x} x}"
but to ensure that your function is stable and adaptable to different functions would be very difficult.
For more details about how value have a look here: https://code.kx.com/q/ref/metadata/#value
For ssr check this link:
https://code.kx.com/q/ref/strings/#ssr

sqrt function gets error in racket

I'm trying to build a simple function that gets a number, checks if the number is more the zero and return the square root of the number:
#lang pl 03
(: sqrtt: Number -> Number)
(define (sqrtt root)
(cond [(null? root) error "no number ~s"]
[( < root 0) error "`sqrt' requires a non-negative input ~s"]
[else (sqrt root)]))
but the result I get when I'm trying to compile the function is:
type declaration: too many types after identifier in: (: sqrtt: Number
-> Number)
Why am I getting that error and how do I fix it?
Try this:
(define (sqrtt root)
(cond [(null? root) (error "no number ~s")]
[(< root 0) (error "`sqrt' requires a non-negative input ~s")]
[else (sqrt root)]))
You simply forgot the () around error. Remember that error is a procedure and, like all other procedures, to apply it you have to surround it with parentheses together with its arguments.
The error message you're getting tells you that you have too many types after an identifier in a : type declaration. Now in racket, sqrtt: counts as an identifier. What you probably meant was sqrtt :, with a space in between.
(: sqrtt : Number -> Number)
The difference is that type declarations of the form (: id : In ... -> Out) are treated specially, but those of the form (: id In ... -> Out) are not. And sqrtt: is counts as the id.
There's also the problem Oscar Lopez pointed out, where you're missing parens around the error calls. Whenever you call a function in racket, including error, you need to wrap the function call in parens.
Also, the (null? root) clause is useless, since root has the type Number and null? will always return false for numbers.
And another thing, depending on what the pl language does, if you get a type error from < afterwards, that's because < operates on only Real numbers, but the Number type can include complex numbers. So you might have to change the type to Real or something.

append if element in list

I'm trying to create a parser for program. For example,
I entered (what I want)
"(2+3)-4" it will become something like this "(minus, (plus, num 2, num 3),num 4)"
What I've done so far..
"(2+3)-4" I then split it and it becomes list Z = ["(","2","+","3",")","-","4"] then I compared if "-" is a member of Z, if true I append the element "-" into a new list ["-"]
I'm not sure if the way I'm doing is correct, I'm new to Er-lang and struggling quite a lot. If anyone is able to offer me some insight, thanks.
Consider the following, which returns a tuple-based representation of its input:
parse(Expr) ->
Elems = re:split(Expr, "([-+)(])", [{return,list}]),
parse(lists:filter(fun(E) -> E /= [] end, Elems), []).
parse([], [Result]) ->
Result;
parse([], [V2,{op,Op},V1|Tacc]) ->
parse([], [{Op,V1,V2}|Tacc]);
parse(["("|Tail], Acc) ->
parse(Tail, [open|Acc]);
parse([")"|Tail], [Op,open|TAcc]) ->
parse(Tail, [Op|TAcc]);
parse(["+"|Tail], Acc) ->
parse(Tail, [{op,plus}|Acc]);
parse(["-"|Tail], Acc) ->
parse(Tail, [{op,minus}|Acc]);
parse([V2|Tail], [{op,Op},V1|Tacc]) ->
parse(Tail, [{Op,V1,{num,list_to_integer(V2)}}|Tacc]);
parse([Val|Tail], Acc) ->
parse(Tail, [{num,list_to_integer(Val)}|Acc]).
The first function, parse/1, splits the expression along the + and - operators and parentheses, preserving these in the resulting list. It then filters that list to remove empty elements, and passes it with an empty accumulator to parse/2.
The parse/2 function has eight clauses, described below:
The first two handle the case when the parsed input list has been exhausted. The second of these handles the case where multiple elements in the accumulator need to be collapsed into a single tuple consisting of operator and operands.
The next two handle clauses parentheses. When we see an open parenthesis, we push an atom open into the accumulator. Upon seeing the matching close parenthesis, we expect to see an operation tuple and the atom open in the accumulator, and we replace them with just the tuple.
Clauses 5 and 6 handle + and - respectively. Each just pushes a {op,Operator} tuple into the accumulator, where Operator is either the atom plus or the atom minus.
The final two clauses handle values. The first one handles the case where the accumulator holds a value and an op tuple, which gets replaced with a full operation tuple consisting of the atom plus or minus followed by two num tuples each holding integer operands. The last clause just handles plain values.
Putting this in a module p, compiling it, and running it in an Erlang shell yields the following:
1> p:parse("2+3").
{plus,{num,2},{num,3}}
2> p:parse("(2+3)-4").
{minus,{plus,{num,2},{num,3}},{num,4}}

Calling a Clojure function with string inside swap?

The macro, transform!, as defined below seems to work for => (transform! ["foo" 1 2 3]). The purpose is to take in a list, with the first element being a string that represents a function in the namespace. Then wrapping everything into swap!.
The problem is that transform! doesn't work for => (transform! coll), where (def coll ["foo" 1 2 3]). I am getting this mystery exception:
#<UnsupportedOperationException java.lang.UnsupportedOperationException: nth not supported on this type: Symbol>
The function:
(defmacro transform!
" Takes string input and update data with corresponding command function.
"
[[f & args]] ;; note double brackets
`(swap! *image* ~(ns-resolve *ns* (symbol f)) ~#args))
I find it strange that it works for one case and not the other.
Macros work at compile-time and operate on code, not on runtime data. In the case of (transform! coll), the macro is being passed a single, unevaluated argument: the symbol coll.
You don't actually need a macro; a regular function will suffice:
(defn transform! [[f & args]]
(apply swap! *image* (resolve (symbol f)) args)))
Resolving vars at runtime could be considered a code smell, so think about whether you really need to do it.
You're passing a symbol to the macro, namely coll. It will try to pull that symbol apart according to the destructuring statement [f & args], which won't be possible of course.
You can also use (resolve symbol) instead of (ns-resolve *ns* symbol).