i've been pulling my hair trying to figure this out. i'm suppose to design a function takes in a hstudent, i get another student with the same contents and with his age converted into dog years. any ideas on how to start? This exact question is going to be on an open book test I have on Friday.
(define-struct hsstudent (first-name last-name classroom overall-grade age))
(define hsstudent1 (make-hsstudent "Randy" "Smith" 'WH '-A 14))
(define hsstudent2 (make-hsstudent "Jon" "James" 'AH '-A 13 ))
(define hsstudent3 (make-hsstudent "Alex" "Manzi" 'LO '+A 16))
(define hsstudent4 (make-hsstudent "Kevin" "Matthews" 'WH '-A 14))
(define hsstudent5 (make-hsstudent "Issac" "Lewis" 'AH '-A 13 ))
(define hsstudent6 (make-hsstudent "Michael" "Gabbin" 'LO '+A 16))
Note: when you say design, that implies you're in a HTDP-based course.
You should already have been introduced to a very concrete set of steps to follow for designing functions that consume and produce structures. Have you looked at Designing with Structures and followed the steps there? If so, are you stuck at any particular step listed here?
The purpose of this methodology is to help pinpoint conceptual problems as soon as possible, rather than at coding time.
What you could do is use the struct selectors to get the values from the student and then give those to make-hsstudent in order to make a new student. For example
(hsstudent-age hsstudent1)
Will return 14. Generally (hsstudent-FIELDNAME student) will give the field value of FIELDNAME for student.
Related
I just finished taking an entry placement test for computer science as in college. I passed, but missed a bunch of questions in a specific category: variable assignment. I want to make sure I understand this before moving on.
It started out with easy things, like "set age equal to age"
int age = 18, pretty simple
But then, it had a question which I had no clue how to approach. It went something like...
"Determine if character c is is in alphabet and assign to a variable"
I could easily do that with a function, but the issue is, it gave me literally a line to write my entire answer (so about 50 characters max). Here is how the answer box looked:
My first thought was to do something like
in_alphabet = function(c) {
var alphabet = ["a", "b" ... "z"]
if(alphabet.indexOf(c) != -1)
return true;
}
But this solution has two issues:
How can I set the "c" value when the whole function is equal to in_alphabet?
I can't fit this into the small answer box. I am 99% sure they were looking for something else. Does anybody know what they were looking for? I can't think of a one line solution for this
Language doesn't matter (although a solution in java/c++ would be preferred). I would appreciate any guidance (doesn't have to be a solution, I just don't even know where to begin)
The question "Determine if character c is is in alphabet and assign to a variable" does not ask you to create a function (although in many languages this would be the best way to do this).
In R you could do something like:
inAlphabet <- c %in% letters
So you can certainly do it in one line in some real-world languages. Note that letters is a built-in list of characters.
It's a VBA solution and returns C in the variable:
LetterC = Mid("ABCDEFGHIJKLMNOPQRSTUVWXYZ", InStr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "C"), 1)
Is that what you're after?
Many languages have a data type that represents a single character, and they often can be compared using binary operators like < > <= >=, wherein the characters are compared numerically.
So something like this should suffice:
in_alphabet = c >= 'a' && c <= 'z'
And some languages already have built in methods to do things similar to this (e.g., Character.isLetter).
I copied straight from How to check if character is a letter in Javascript?
in_alphabet = c.length === 1 && c.match(/[a-z]/i)? str : ""
In Java, Character.isLetter(c)
In .NET, Char.IsLetter(c)
Perhaps you were being tested on knowledge of basic data types and some of the facilities they provide.
I've just started learning Scheme and I'm having some trouble. I am using petite chez scheme (64-bit) with Windows. I have been reading up on examples using the functions 'every' , 'keep' and 'accumulate' , which I understand are built in and known by petite (i.e. do not have to be defined before use). However when I enter the examples I have read to test them, an error is returned. For example-
;; To make nouns plural
(define (plural noun)
(if (equal? (last noun) ’y)
(word (bl noun) ’ies)
(word noun ’s)))
> (every plural ’(beatle turtle holly kink zombie)) ;; Example input
(BEATLES TURTLES HOLLIES KINKS ZOMBIES) ;; Expected output
Instead I receive the error "variable every is not bound". It is as if 'every' is being treated as a variable rather than a known function. I receive the same error when I try examples with 'keep' and 'accumulate'. The coding is correct I assume (since it is copied from the book I'm reading). Am I wrong in thinking that these functions are built in and do not need to be defined or is there some other issue? Hope someone can shed some light on this.
The every procedure is defined in SRFI-1 and is not part of the standard language. Refer to this project for the SRFIs available in Chez Scheme.
And besides, I don't think every is the procedure you're looking for, what you want to do is a map - please check the documentation first!
(map plural '(beatle turtle holly kink zombie))
I am beginner in Haskell .
The convention used in function definition as per my school material is actually as follows
function_name arguments_separated_by_spaces = code_to_do
ex :
f a b c = a * b +c
As a mathematics student I am habituated to use the functions like as follows
function_name(arguments_separated_by_commas) = code_to_do
ex :
f(a,b,c) = a * b + c
Its working in Haskell .
My doubt is whether it works in all cases ?
I mean can i use traditional mathematical convention in Haskell function definition also ?
If wrong , in which specific cases the convention goes wrong ?
Thanks in advance :)
Let's say you want to define a function that computes the square of the hypoteneuse of a right-triangle. Either of the following definitions are valid
hyp1 a b = a * a + b * b
hyp2(a,b) = a * a + b * b
However, they are not the same function! You can tell by looking at their types in GHCI
>> :type hyp1
hyp1 :: Num a => a -> a -> a
>> :type hyp2
hyp2 :: Num a => (a, a) -> a
Taking hyp2 first (and ignoring the Num a => part for now) the type tells you that the function takes a pair (a, a) and returns another a (e.g it might take a pair of integers and return another integer, or a pair of real numbers and return another real number). You use it like this
>> hyp2 (3,4)
25
Notice that the parentheses aren't optional here! They ensure that the argument is of the correct type, a pair of as. If you don't include them, you will get an error (which will probably look really confusing to you now, but rest assured that it will make sense when you've learned about type classes).
Now looking at hyp1 one way to read the type a -> a -> a is it takes two things of type a and returns something else of type a. You use it like this
>> hyp1 3 4
25
Now you will get an error if you do include parentheses!
So the first thing to notice is that the way you use the function has to match the way you defined it. If you define the function with parens, you have to use parens every time you call it. If you don't use parens when you define the function, you can't use them when you call it.
So it seems like there's no reason to prefer one over the other - it's just a matter of taste. But actually I think there is a good reason to prefer one over the other, and you should prefer the style without parentheses. There are three good reasons:
It looks cleaner and makes your code easier to read if you don't have parens cluttering up the page.
You will take a performance hit if you use parens everywhere, because you need to construct and deconstruct a pair every time you use the function (although the compiler may optimize this away - I'm not sure).
You want to get the benefits of currying, aka partially applied functions*.
The last point is a little subtle. Recall that I said that one way to understand a function of type a -> a -> a is that it takes two things of type a, and returns another a. But there's another way to read that type, which is a -> (a -> a). That means exactly the same thing, since the -> operator is right-associative in Haskell. The interpretation is that the function takes a single a, and returns a function of type a -> a. This allows you to just provide the first argument to the function, and apply the second argument later, for example
>> let f = hyp1 3
>> f 4
25
This is practically useful in a wide variety of situations. For example, the map functions lets you apply some function to every element of a list -
>> :type map
map :: (a -> b) -> [a] -> [b]
Say you have the function (++ "!") which adds a bang to any String. But you have lists of Strings and you'd like them all to end with a bang. No problem! You just partially apply the map function
>> let bang = map (++ "!")
Now bang is a function of type**
>> :type bang
bang :: [String] -> [String]
and you can use it like this
>> bang ["Ready", "Set", "Go"]
["Ready!", "Set!", "Go!"]
Pretty useful!
I hope I've convinced you that the convention used in your school's educational material has some pretty solid reasons for being used. As someone with a math background myself, I can see the appeal of using the more 'traditional' syntax but I hope that as you advance in your programming journey, you'll be able to see the advantages in changing to something that's initially a bit unfamiliar to you.
* Note for pedants - I know that currying and partial application are not exactly the same thing.
** Actually GHCI will tell you the type is bang :: [[Char]] -> [[Char]] but since String is a synonym for [Char] these mean the same thing.
f(a,b,c) = a * b + c
The key difference to understand is that the above function takes a triple and gives the result. What you are actually doing is pattern matching on a triple. The type of the above function is something like this:
(a, a, a) -> a
If you write functions like this:
f a b c = a * b + c
You get automatic curry in the function.
You can write things like this let b = f 3 2 and it will typecheck but the same thing will not work with your initial version. Also, things like currying can help a lot while composing various functions using (.) which again cannot be achieved with the former style unless you are trying to compose triples.
Mathematical notation is not consistent. If all functions were given arguments using (,), you would have to write (+)((*)(a,b),c) to pass a*b and c to function + - of course, a*b is worked out by passing a and b to function *.
It is possible to write everything in tupled form, but it is much harder to define composition. Whereas now you can specify a type a->b to cover for functions of any arity (therefore, you can define composition as a function of type (b->c)->(a->b)->(a->c)), it is much trickier to define functions of arbitrary arity using tuples (now a->b would only mean a function of one argument; you can no longer compose a function of many arguments with a function of many arguments). So, technically possible, but it would need a language feature to make it simple and convenient.
For the following code:
(foldl and #t '(#t #f))
Racket returns:
and: bad syntax in: and
I know and is not a function. And I can circumvent this problem using lambda:
(foldl (lambda (a b) (and a b)) #t '(#t #f))
I have 2 questions here:
and is not a function. Then what is it? Is it a macro?
My solution using lambda seems ugly. Is there a better way to solve this problem?
Thank you.
It is a conditional syntactic form, or it might be implemented as a macro that expands to some core syntax form, which is treated as a special case by the compiler/interpreter.
The list there in Racket's docs includes if as a special form but doesn't include and, so the latter most probably is implemented in terms of the former. But R5RS does list and as a syntactic keyword. So, best we can say, it's either a special syntax, or a macro.
It is easy to re-write any and form (and a b c ...) as an if form, (if a (if b (if c #t #f) #f) #f).
lambda is fine by me, but you can also use every from SRFI-1 (or Racket's andmap):
(every identity '(#t #f))
should return #f.
edit: except, as Joshua Taylor points out, calling your lambda through a function like foldl does not short-circuit. Which defeats the purpose to calling the and in the first place.
Another thing is, in Racket's foldl the last argument to lambda is the one that receives the previous result in the chain of applications; so the implementation should really be
(foldl (lambda (a b) (and b a)) #t '(#t #f))
I am starting to learn Lua from Programming in Lua (2nd edition) I didn't understand the following in the book.
network = {
{name ="grauna", IP="210.26.30.34"},
{name ="araial", IP="210.26.30.23"},
}
If we want to sort the table by field name, the author mentions
table.sort(network, function (a,b) return (a.name > b.name) end }
Whats happening here? What does function (a,b) stand for? Is function a key word or something.
If was playing around with it and created a table order
order={x=1,x=22,x=10} // not sure this is legal
and then did
print (table.sort(order,function(a,b) return (a.x > b.x) end))
I did not get any output. Where am I going wrong?
Thanks
It's an anonymous function that takes two arguments and returns true if the first argument is less than the second argument. table.sort() runs this function for each of the elements that need sorting and compares each element with the previous element.
I think (but I am not sure) that order={x=1,x=22,x=10} has the same meaning in Lua as order={x=10}, a table with one key "x" associated with the value 10. Maybe you meant {{x=1},{x=22},{x=10}} to make an "array" of 3 components, each having the key "x".
To answer the second part of your question: Lua is very small, and doesn't provide a way to print a table directly. If you use a table as a list or array, you can do this:
print(unpack(some_table))
unpack({1, 2, 3}) returns 1, 2, 3. A very useful function.
function in lua is a keyword, similar to lambda in Scheme or Common Lisp (& also Python), or fun in Ocaml, to introduce anonymous functions with closed variables, i.e. closures