Using ML (or Scheme or some “functional-algorithm-language” like ML or Scheme),
ID: 3721859 • Letter: U
Question
Using ML (or Scheme or some “functional-algorithm-language” like ML or Scheme), define the following functions:
a) evens(X) to create a list consisting of every other element in X starting with the second one (2st, 4rd , etc.) It should return empty list if X does not have at least two items
b) last (X) to return the last value in list X
c) double (X) to double each item in list X
d) cnt (a,X) to count how many times a appears in X.
e) less (a,X) to create a list consisting of all integers in X that are less than a.
Explanation / Answer
Solution:
a)
a) evens(X) to create a list consisting of every other element in X starting with the second one (2st, 4rd , etc.) It should return empty list if X does not have at least two items
evens x | length(x) < 1 = []
| otherwise = evens' x
evens' [] = []
evens' [a] = []
evens' (a:b:x) = b:(evens' x)
b) last (X) to return the last value in list X
lastt [] = undefined
lastt [a] = a
lastt (a:x) = lastt x
c) double (X) to double each item in list X
double1 [] = [] -- if you mean double is trepeat o each element again
double1 (a:x) = a:a:(double1 x)
double2 [] = [] -- if you mean double is to multiply each element by 2
double2 (a:x) = (2*a):(double2 x)
d) cnt (a,X) to count how many times a appears in X.
cnt a [] = 0
cnt a (v:x) | a == v = 1+(cnt a x)
| otherwise = cnt a x
e) less (a,X) to create a list consisting of all integers in X that are less than a.
less a [] = []
less a (v:x) | v<a = v:(less a x)
| otherwise = less a x
I hope this helps if you find any problem. Please comment below. Don't forget to give a thumbs up if you liked it. :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.