I'm tring to convert the following 3 methods from java-actionscript to Objective C.
Part of my confusion I think is not knowing what Number types, primitives I should be using. ie in actionscript you have only Number, int, and uint. These are the 3 functions I am trying to convert
public function normalize(value:Number, minimum:Number, maximum:Number):Number
{
return (value - minimum) / (maximum - minimum);
}
public function interpolate(normValue:Number, minimum:Number, maximum:Number):Number
{
return minimum + (maximum - minimum) * normValue;
}
public function map(value:Number, min1:Number, max1:Number, min2:Number, max2:Number):Number
{
return interpolate( normalize(value, min1, max1), min2, max2);
}
This is what I have so far
-(float) normalize:(float*)value
withMinimumValue:(float*)minimum
withMaximumValue:(float*)maximum
{
return (value - minimum) / (maximum - minimum);
}
-(float) interpolate:(float*)normValue
withMinimumValue:(float*)minimum
withMaximumValue:(float*)maximum
{
return minimum + (maximum - minimum) * normValue;
}
-(float) map:(float*)value
withMinimumValue1:(float*)min1
withMaximumValue1:(float*)max1
withMinimumValue2:(float*)min2
withMaximumValue2:(float*)max2
{
return interpolate( normalize(value, min1, max1), min2, max2);
}
If you're looking for a primitive type (not an object) that can handle non-integer values, float is probably fine (or CGFloat, as suggested by Chris)
unless your functions need to modify their arguments, you want the arguments to be just float not float *.
you are mixing up Objective-C message passing and plain C function invocation syntax: your example declares them as instance methods, but you're calling them like a function (won't work).
To match your declarations, the invocation would look something like:
return [self interpolate:
[self normalize:value withMinimumValue:min1 withMaximumValue:max1]
withMinimumValue:min2
withMaximumValue:max2];
Because your interpolate, normalize, and map methods do not rely on any variables from the current object instance, they might be better off as objective-C class methods (or even as plain C functions).
Given that none of your methods require any other state to work, all are basic math kinda stuff, and all are pretty straightforward, I would skip Objective-C entirely and just go with straight C. Something like:
static inline float normalize(float val, float min, float max) {
return (val - min) / (max - min);
}
Stick that in a header file somewhere in your project and be done with it. Do the same for interpolate and map.
Note: as others have mentioned, you might want to change the type to CGFloat, if needed.
Assuming you're using Apple's frameworks, these are the conversions you'll probably want to use:
Number =~ CGFloat
int =~ NSInteger
uint =~ NSUInteger
Related
Is there any declarative work around to exclude last item while decrementing looping, like using downTo?
While the kotlin standard library does not include this utility, you can define your own extension functions for this purpose.
Looking at the stdlib, one definition of until is:
/**
* Returns a range from this value up to but excluding the specified [to] value.
*
* If the [to] value is less than or equal to `this` value, then the returned range is empty.
*/
public infix fun Int.until(to: Int): IntRange {
if (to <= Int.MIN_VALUE) return IntRange.EMPTY
return this .. (to - 1).toInt()
}
Therefore, we could define
infix fun Int.downUntil(to: Int): IntProgression {
if (to >= Int.MAX_VALUE) return IntRange.EMPTY
return this downTo (to + 1).toInt()
}
You may also want to define versions of this function to operate on other primitives.
for ( number in (0 until 10).reversed()) {
println("$number using range until reversed")
}
Even I was looking for downTo but didn't find but above implementation works
Can I declare a C function with an undetermined return type (without C compiler warning)? The return type could be int, float, double, void *, etc.
undetermined_return_type miscellaneousFunction(undetermined_return_type inputValue);
And you can use this function in other functions to return a value (although that could be a run time error):
BOOL isHappy(int feel){
return miscellaneousFunction(feel);
};
float percentage(float sales){
return miscellaneousFunction(sales);
};
What I'm looking for:
To declare and to implement a C function (or Obj-C method) with an undefined-return-type could be useful for aspect-oriented programming.
If I could intercept Obj-C messages in another function in run time, I might return the value of that message to the original receiver or not with doing something else action. For example:
- (unknown_return_type) interceptMessage:(unknown_return_type retValOfMessage){
// I may print the value here
// No idea how to print the retValOfMessage (I mark the code with %???)
print ("The message has been intercepted, and the return value of the message is %???", retValOfMessage);
// Or do something you want (e.g. lock/unlock, database open/close, and so on).
// And you might modify the retValOfMessage before returning.
return retValOfMessage;
}
So I can intercept the original message with a little addition:
// Original Method
- (int) isHappy{
return [self calculateHowHappyNow];
}
// With Interception
- (int) isHappy{
// This would print the information on the console.
return [self interceptMessage:[self calculateHowHappyNow]];
}
You can use a void * type.
Then for example:
float percentage(float sales){
return *(float *) miscellaneousFunction(sales);
}
Be sure not to return a pointer to a object with automatic storage duration.
You may use the preprocessor.
#include <stdio.h>
#define FUNC(return_type, name, arg) \
return_type name(return_type arg) \
{ \
return miscellaneousFunction(arg); \
}
FUNC(float, undefined_return_func, arg)
int main(int argc, char *argv[])
{
printf("\n %f \n", undefined_return_func(3.14159));
return 0;
}
May be a union as suggested by thejh
typedef struct
{
enum {
INT,
FLOAT,
DOUBLE
} ret_type;
union
{
double d;
float f;
int i;
} ret_val;
} any_type;
any_type miscellaneousFunction(any_type inputValue) {/*return inputValue;*/}
any_type isHappy(any_type feel){
return miscellaneousFunction(feel);
}
any_type percentage(any_type sales){
return miscellaneousFunction(sales);
}
Here with ret_type you can know data type of return value and ret_type. i,f,d can give you corresponding value.
All elements will use same memory space and only one should be accessed.
Straight C doesn't support dynamically-typed variables (variants) since it is statically typed, but there might be some libraries that do what you want.
When declaring a block what's the rationale behind using this syntax (i.e. surrounding brackets and caret on the left)?
(^myBlock)
For example:
int (^myBlock)(int) = ^(int num) {
return num * multiplier;
};
C BLOCKS: Syntax and Usage
Variables pointing to blocks take on the exact same syntax as variables pointing to functions, except * is substituted for ^. For example, this is a function pointer to a function taking an int and returning a float:
float (*myfuncptr)(int);
and this is a block pointer to a block taking an int and returning a float:
float (^myblockptr)(int);
As with function pointers, you'll likely want to typedef those types, as it can get relatively hairy otherwise. For example, a pointer to a block returning a block taking a block would be something like void (^(^myblockptr)(void (^)()))();, which is nigh impossible to read. A simple typedef later, and it's much simpler:
typedef void (^Block)();
Block (^myblockptr)(Block);
Declaring blocks themselves is where we get into the unknown, as it doesn't really look like C, although they resemble function declarations. Let's start with the basics:
myvar1 = ^ returntype (type arg1, type arg2, and so on) {
block contents;
like in a function;
return returnvalue;
};
This defines a block literal (from after = to and including }), explicitly mentions its return type, an argument list, the block body, a return statement, and assigns this literal to the variable myvar1.
A literal is a value that can be built at compile-time. An integer literal (The 3 in int a = 3;) and a string literal (The "foobar" in const char *b = "foobar";) are other examples of literals. The fact that a block declaration is a literal is important later when we get into memory management.
Finding a return statement in a block like this is vexing to some. Does it return from the enclosing function, you may ask? No, it returns a value that can be used by the caller of the block. See 'Calling blocks'. Note: If the block has multiple return statements, they must return the same type.
Finally, some parts of a block declaration are optional. These are:
The argument list. If the block takes no arguments, the argument list can be skipped entirely.
Examples:
myblock1 = ^ int (void) { return 3; }; // may be written as:
myblock2 = ^ int { return 3; }
The return type. If the block has no return statement, void is assumed. If the block has a return statement, the return type is inferred from it. This means you can almost always just skip the return type from the declaration, except in cases where it might be ambiguous.
Examples:
myblock3 = ^ void { printf("Hello.\n"); }; // may be written as:
myblock4 = ^ { printf("Hello.\n"); };
// Both succeed ONLY if myblock5 and myblock6 are of type int(^)(void)
myblock5 = ^ int { return 3; }; // can be written as:
myblock6 = ^ { return 3; };
source: http://thirdcog.eu/pwcblocks/
I think the rationale is that it looks like a function pointer:
void (*foo)(int);
Which should be familiar to any C programmer.
I want make a function to include in my code to calculate percentages.
In Php, it's :
function percent(a,b){
return a/b*100;
}
In Objective C, I don't know. I tried:
-(void)percent(a,b){
return a/b*100;
}
But there are 2 errors. Could you me explain how to make it work?
Thank you for you help
A method is defined in a slightly different syntax than you're used to:
- (float)percentWithA:(float)a dividedByB:(float)b
{
return a / b * 100;
}
The parameters are "strewn" throughout the method call. For instance, this method's name would be percentWithA:dividedByB:. You don't need to be as explicit as this call, however. For example, you could do this:
- (float)percent:(float)a :(float)b { /* ... */ }
But it doesn't provide much context.
The more correct way to do this will be:
- (float)precentageByDevidingFloat:(float)a byFloat:(float)b {
float returnValue = 0;
if (b != 0)
returnValue = a / b * 100;
return returnValue;
}
This way you use a more correct naming convention , you actually return a float and your safe in case some one gave you the value 0 in B.
(which should be covered by documentation)
You could also do it like this, with a C function:
// in your .h
float percent(float a, float b);
// in your .m or .c
float percent(float a, float b)
{
return a / b * 100.0f;
}
Or, if you are into macros:
// remember to always enclose macros in parentheses
#define percent(a, b) (a / b * 100.0f)
And you would call it like this:
percent(50, 20);
Objective-C uses a strange convention of having parameter names as part of a method name and therefore parameter declarations are embedded in a method name.
-(float)percentOf:(float)a over:(float)b
{
return (a/b) * 100.0;
}
The first type in parentheses defines the return type, the parameters come after colons and also have their type in parentheses.
I need to implement kind of illustrated function ( ratio = somefunction(time)) in Objective-c. Language doesn't actually matters, because task seems purely algorithmic. Is there any common way to do things like this?
Next things should be easily adjustable in process of design:
1) Number of small intervals per period (now it 4, but it can be 3 or 20 for example).
2) f1 can be changed. It's simple function like f(x) = sin(x).
3) if we say
f_resulting =
f1 for a time t1
f2 for a time t2
then again
f1 for a time t1
etc..
ratio when f1 "works" vs f2 "works" (t1 to t2) should be adjustable.
Standard C itself has no closures so if you use C function pointers you need to build your own closure - you just use a class instance to store the two function pointers and duration and an invoke method to call the composed periodic function.
However Apple has introduced blocks, which are just inline functions implemented with closures, so in Apple C you can easily compose functions. This is more interesting, but "best" you will have to decide...
An example which composes double -> double functions. First the header, Periodic.h:
typedef double (^Monadic)(double);
Monadic makePeriodic(Monadic firstFunction, double firstPeriod,
Monadic secondFunction, double secondPeriod);
And the implementation, Periodic.c:
#include "Periodic.h"
Monadic makePeriodic(Monadic firstFunction, double firstPeriod,
Monadic secondFunction, double secondPeriod)
{
return Block_copy(^(double time)
{
return fmod(time, firstPeriod+secondPeriod) < firstPeriod
? firstFunction(time)
: secondFunction(time);
}
);
}
Blocks are constructed on the stack and can reference local variables and parameters in the enclosing scope. As such you cannot simply return a block from a function as the scope it refers to disappears on return. The function Block_copy() moves a block, and any blocks it refers to, onto the heap allowing them to outlive their creating scope. A heap block must be released with Block_release() when no longer needed.
And a simple demo:
Monadic queer = makePeriodic(^(double t) { return t * t; }, 5,
^(double t) { return sqrt(t); }, 3);
for(double ix = 0; ix <= 16; ix++)
printf("%f -> %f\n", ix, queer(ix));
Block_release(queer); // clean up
Now you can wrap all this up in a class if you wish so it fits Obj-C style. When you do this you can also send copy and release messages to the block, just as if it was an Obj-C object. In a garbage collected environment you still need the copy to get thge block onto the heap, but the release is not needed.
Periodic.h:
typedef double (^Monadic)(double);
#interface ComposeOne : NSObject
{
}
+ (Monadic) makePeriodicWithFunction:(Monadic)firstFunction
forPeriod:(double)firstPeriod
andFunction:(Monadic)secondFunction
forPeriod:(double)secondPeriod;
#end
Periodic.M:
#implementation ComposeOne
+ (Monadic) makePeriodicWithFunction:(Monadic)firstFunction
forPeriod:(double)firstPeriod
andFunction:(Monadic)secondFunction
forPeriod:(double)secondPeriod
{
Monadic result = (^(double time)
{
return fmod(time, firstPeriod+secondPeriod) < firstPeriod
? firstFunction(time)
: secondFunction(time);
}
);
return [result copy];
}
#end
And the simple demo (still using printf though for convenience):
Monadic queer = [ComposeOne makePeriodicWithFunction:^(double t) { return t * t; }
forPeriod:5
andFunction:^(double t) { return sqrt(t); }
forPeriod:3];
for(double ix = 0; ix <= 16; ix++)
printf("%f -> %f\n", ix, queer(ix));
[queer release];