Hello.. please I need some help doing the following: ** We can introduce a new E
ID: 3776915 • Letter: H
Question
Hello.. please I need some help doing the following:
** We can introduce a new Elm type for the natural numbers (i.e., nonnegative integers) with the definition
where the constructor Zero represents the integer value 0 and constructor Succ represents the “successor function” from mathematics. Thus (Succ Zero) denotes 1, (Succ (Succ Zero)) denotes 2, and so forth.
We can define an Elm function natToInt that takes a Nat and returns the equivalent value of type Int as follows:
Write the following Elm functions:
a) intToNat that takes a nonnegative Int and returns the equivalent Nat, for example, 3 returns Succ (Succ (Succ Zero))
b) addNat that takes two Nat values and returns their sum as a Nat. This function cannot use the builtin integer or floating point addition
Extend the above example by doing ONE of the following:
a) compNat that takes two Nat values and returns the value -1 if the first is less than the second, 0 if they are equal, and 1 if the first is greater than the second. This function cannot use the integer comparison operators.
b) mulNat that takes two Nat values and returns their product as a Nat. This function cannot use the builtin integer or floating point operations. (Hint: You may want to use addNat.)
Explanation / Answer
add : Int -> Int -> Int
add x y =
x + y
##call add 1 3
mul : Int -> Int -> Int
mul x y =
x * y
##call mul 4 3
Compare: Int -> Int -> Int
if x < y then
-1
else if y < x then
1
else
0
repeat' : Int -> a -> List a
repeat' n x =
if n <= 0 then
[]
else
x :: repeat' (n-1) x
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.