Objectives: To better understand how simple operations work in a modern function
ID: 3791880 • Letter: O
Question
Objectives: To better understand how simple operations work in a modern functional-oriented programming language. Once again, you will be left to your own devices to figure out how to use Clojure. Assignment (part 1): There are 2 parts to this assignment. First, you need to write two Clojure functions, mcompute() and lcompute(), When used, such as by the program below: (println (mcompute say hello 30 20)) (println (mcompute add" (mcompute sub 70 40) 20)) (println (mcompute sub 30 20)) (println (mcompute loop 1 5)) (println (mcompute equalorLarger 10 5) (println (mcompute equalorLarger 5 5)) (println (mcompute equalor Larger 5 15) (println (lcompute insert 7 1 2 3 1 (println (lcompute append 7 1 2 31)) The result is hi there 30 and 20 nice to meet you 50 10 (1 2 3 4 5) true true false (7 1 2 3) (1 2 3 7) Note: 1 pt extra credit if you can generate (1 49 16 25) by adding a "lsqr" operation to mcompute, which should produce the square of every number in the list. For example, (println (mcompute loop 1 5) should produce: (1 49 16 25) Assignment (part 2): In a paragraph, explain (a) what "immutable" means and (b) one reason why it is beneficial.Explanation / Answer
def mcompute(command,val1,val2):
if command=='sayhello':
return ('hello {0} and {1}, nice to meet you.'.format(val1,val2))
if command=='add':
return val1+val2
if command=='sub':
return val1-val2
if command=='loop':
return "".join([str(i) for i in range(val1,val2+1)])
if command=='equalOrLarger':
if val1>=val2:
return True
else:
return False
def lcompute(command,val1,lst):
if command=='find':
for loc,x in enumerate(lst):
if x == val1:
return loc
if command=='add':
lst.append(val1)
return lst
if command=='del':
for i in range(len(lst)):
if lst[i]==val1:
del lst[i]
return lst
print(mcompute("sayhello",30,20))
print(mcompute("add",mcompute("sub",70,40),20))
print(mcompute("sub",30,20))
print(mcompute("loop",1,5))
print(mcompute("equalOrLarger",10,5))
print(mcompute("equalOrLarger",5,5))
print(mcompute("equalOrLarger",5,15))
print(lcompute("find",1,[1,2,3]))
print(lcompute("find",3,[1,2,3]))
print(lcompute("add",7,[1,2,3]))
print(lcompute("del",3,[1,2,3]))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.