Problem Solving
In this problem, we will use the HtDF method to create a function.
Problem: Design a function that pluralizes a given word. (Pluralize means to convert the word to its plural form.) For simplicity you may assume that just adding s is enough to pluralize a word.
Here is the problem that we need to convert into a function. We need to do it systematically using the HtDF method.
First we need the signature, recall that the signature will tell us what is the input and expected output. A word is the input and output of the function, and we can represent words, which is just a sequence of characters if you think about it, like a String.
So the signature of the function is
;;String -> String
Then we will need to know what is the function's purpose, we can look at the specifications to know the purpose.
It says that the word is pluralized in the process "assumption that adding s at the end is the pluralized form of the word". Therefore the purpose would be that it would produce a string with s added to the end.
You would need to be very specific with the purpose on what it really does, so that things would be clear when coding the function body.
We need a stub, which would apply what we have at the signature of the function. It inputs a string as a parameter and outputs a string.
(define (pluralize str) "")
Now our stub fulfills the requirements set by the signature.
Then we need to make some examples or test cases on what the expected output would be. Here, i used rackets testing framework.
(check-expect (pluralize "dog") "dogs")
(check-expect (pluralize "grass") "grasss")
For the template, it is just going to be (... str) since we are just going to do something to the str value.
Now we can code the function body, recall that the purpose of the function is to add an s to the end of the string and output the result. We can use the string-append primitive to concatenate the strings
(string-append str "s")
And we have finished the function.
Mga Komento
Mag-post ng isang Komento