Search Results

Search found 83 results on 4 pages for 'ternary'.

Page 1/4 | 1 2 3 4  | Next Page >

  • Other ternary operators besides ternary conditional (?:)

    - by Malcolm
    The "ternary operator" expression is now almost equivalent to the ternary conditional operator: condition ? trueExpression : falseExpression; However, "ternary operator" only means that it takes three arguments. I'm just curious, are there any languages with any other built-in ternary operators besides conditional operator and which ones?

    Read the article

  • Java ternary operator and boxing Integer/int?

    - by Markus
    I tripped across a really strange NullPointerException the other day caused by an unexpected type-cast in the ternary operator. Given this (useless exemplary) function: Integer getNumber() { return null; } I was expecting the following two code segments to be exactly identical after compilation: Integer number; if (condition) { number = getNumber(); } else { number = 0; } vs. Integer number = (condition) ? getNumber() : 0; . Turns out, if condition is true, the if-statement works fine, while the ternary opration in the second code segment throws a NullPointerException. It seems as though the ternary operation has decided to type-cast both choices to int before auto-boxing the result back into an Integer!?! In fact, if I explicitly cast the 0 to Integer, the exception goes away. In other words: Integer number = (condition) ? getNumber() : 0; is not the same as: Integer number = (condition) ? getNumber() : (Integer) 0; . So, it seems that there is a byte-code difference between the ternary operator and an equivalent if-else-statement (something I didn't expect). Which raises three questions: Why is there a difference? Is this a bug in the ternary implementation or is there a reason for the type cast? Given there is a difference, is the ternary operation more or less performant than an equivalent if-statement (I know, the difference can't be huge, but still)?

    Read the article

  • Ternary operator in VB.NET

    - by Jalpesh P. Vadgama
    We all know about Ternary operator in C#.NET. I am a big fan of ternary operator and I like to use it instead of using IF..Else. Those who don’t know about ternary operator please go through below link. http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.80).aspx Here you can see ternary operator returns one of the two values based on the condition. See following example. bool value = false;string output=string.Empty;//using If conditionif (value==true) output ="True";else output="False";//using tenary operatoroutput = value == true ? "True" : "False"; In the above example you can see how we produce same output with the ternary operator without using If..Else statement. Recently in one of the project I was working with VB.NET language and I was eager to know if there is a ternary operator equivalent there or not. After searching on internet I have found two ways to do it. IF operator which works for VB.NET 2008 and higher version and IIF operator which is there since VB 6.0. So let’s check same above example with both of this operators. So let’s create a console application which has following code. Module Module1 Sub Main() Dim value As Boolean = False Dim output As String = String.Empty ''Output using if else statement If value = True Then output = "True" Else output = "False" Console.WriteLine("Output Using If Loop") Console.WriteLine(output) output = If(value = True, "True", "False") Console.WriteLine("Output using If operator") Console.WriteLine(output) output = IIf(value = True, "True", "False") Console.WriteLine("Output using IIF Operator") Console.WriteLine(output) Console.ReadKey() End If End SubEnd Module As you can see in the above code I have written all three-way to condition check using If.Else statement and If operator and IIf operator. You can see that both IIF and If operator has three parameter first parameter is the condition which you need to check and then another parameter is true part of you need to put thing which you need as output when condition is ‘true’. Same way third parameter is for the false part where you need to put things which you need as output when condition as ‘false’. Now let’s run that application and following is the output as expected. That’s it. You can see all three ways are producing same output. Hope you like it. Stay tuned for more..Till then Happy Programming.

    Read the article

  • Ternary operators and variable reassignment in PHP

    - by TomcatExodus
    I've perused the questions on ternary operators vs. if/else structures, and while I understand that under normal circumstances there is no performance loss/gain in using ternary operators over if/else structures, I've not seen any mention of this situation. Language specific to PHP (but any language agnostic details are welcome) does the interpreter reassign values in situations like this: $foo = 'bar' $foo = strlen($foo) > 3 ? substr($foo, 0, 3) : $foo; Since this would evaluate to $foo = $foo; is this inefficient, or does the interpreter simply overlook/discard this evaluation? On a side note, what about: !defined('SECURE') ? exit : null;

    Read the article

  • PHP ternary operator

    - by thecoshman
    ($DAO->get_num_rows() == 1) ? echo("is") : echo("are"); This dose not seem to be working for me,I get an error "Unexpected T_ECHO" I have tried it with out the brackets around the conditional. Am I just not able to use a ternary operator in this way? The $DAO-get_num_rows() returns an integer value. Thanks

    Read the article

  • unusual ternary operation

    - by nik
    Hi, I was asked to perform this operation of ternary operator use: $test='one'; echo $test == 'one' ? 'one' : $test == 'two' ? 'two' : 'three'; Which prints two (checked using php). I am still not sure about the logic for this. Please, can anybody tell me the logic for this.

    Read the article

  • Ternary operators in C#

    - by pm_2
    With the ternary operator, it is possible to do something like the following (assuming Func1() and Func2() return an int: int x = (x == y) ? Func1() : Func2(); However, is there any way to do the same thing, without returning a value? For example, something like (assuming Func1() and Func2() return void): (x == y) ? Func1() : Func2(); I realise this could be accomplished using an if statement, I just wondered if there was a way to do it like this.

    Read the article

  • Why does the Ternary\Conditional operator seem significantly faster

    - by Jodrell
    Following on from this question, which I have partially answered. I compile this console app in x64 Release Mode, with optimizations on, and run it from the command line without a debugger attached. using System; using System.Diagnostics; class Program { static void Main() { var stopwatch = new Stopwatch(); var ternary = Looper(10, Ternary); var normal = Looper(10, Normal); if (ternary != normal) { throw new Exception(); } stopwatch.Start(); ternary = Looper(10000000, Ternary); stopWatch.Stop(); Console.WriteLine( "Ternary took {0}ms", stopwatch.ElapsedMilliseconds); stopwatch.Start(); normal = Looper(10000000, Normal); stopWatch.Stop(); Console.WriteLine( "Normal took {0}ms", stopwatch.ElapsedMilliseconds); if (ternary != normal) { throw new Exception(); } Console.ReadKey(); } static int Looper(int iterations, Func<bool, int, int> operation) { var result = 0; for (int i = 0; i < iterations; i++) { var condition = result % 11 == 4; var value = ((i * 11) / 3) % 5; result = operation(condition, value); } return result; } static int Ternary(bool condition, in value) { return value + (condition ? 2 : 1); } static int Normal(int iterations) { if (condition) { return = 2 + value; } return = 1 + value; } } I don't get any exceptions and the output to the console is somthing close to, Ternary took 107ms Normal took 230ms When I break down the CIL for the two logical functions I get this, ... Ternary ... { : ldarg.1 // push second arg : ldarg.0 // push first arg : brtrue.s T // if first arg is true jump to T : ldc.i4.1 // push int32(1) : br.s F // jump to F T: ldc.i4.2 // push int32(2) F: add // add either 1 or 2 to second arg : ret // return result } ... Normal ... { : ldarg.0 // push first arg : brfalse.s F // if first arg is false jump to F : ldc.i4.2 // push int32(2) : ldarg.1 // push second arg : add // add second arg to 2 : ret // return result F: ldc.i4.1 // push int32(1) : ldarg.1 // push second arg : add // add second arg to 1 : ret // return result } Whilst the Ternary CIL is a little shorter, it seems to me that the execution path through the CIL for either function takes 3 loads and 1 or 2 jumps and a return. Why does the Ternary function appear to be twice as fast. I underdtand that, in practice, they are both very quick and indeed, quich enough but, I would like to understand the discrepancy.

    Read the article

  • Can I create ternary operators in C# ?

    - by Scott S
    I want to create a ternary operator for a < b < c which is a < b && b < c. or any other option you can think of that a < b c and so on... I am a fan of my own shortform and I have wanted to create that since I learned programming in high school. How?

    Read the article

  • Type result with Ternary operator in C#

    - by Vaccano
    I am trying to use the ternary operator, but I am getting hung up on the type it thinks the result should be. Below is an example that I have contrived to show the issue I am having: class Program { public static void OutputDateTime(DateTime? datetime) { Console.WriteLine(datetime); } public static bool IsDateTimeHappy(DateTime datetime) { if (DateTime.Compare(datetime, DateTime.Parse("1/1")) == 0) return true; return false; } static void Main(string[] args) { DateTime myDateTime = DateTime.Now; OutputDateTime(IsDateTimeHappy(myDateTime) ? null : myDateTime); Console.ReadLine(); ^ } | } | // This line has the compile issue ---------------+ On the line indicated above, I get the following compile error: Type of conditional expression cannot be determined because there is no implicit conversion between '< null ' and 'System.DateTime' I am confused because the parameter is a nullable type (DateTime?). Why does it need to convert at all? If it is null then use that, if it is a date time then use that. I was under the impression that: condition ? first_expression : second_expression; was the same as: if (condition) first_expression; else second_expression; Clearly this is not the case. What is the reasoning behind this? (NOTE: I know that if I make "myDateTime" a nullable DateTime then it will work. But why does it need it? As I stated earlier this is a contrived example. In my real example "myDateTime" is a data mapped value that cannot be made nullable.)

    Read the article

  • Ternary and Artificial Intelligence

    - by user2957844
    Not much of a programmer myself, however I have been thinking about the future of AI. If a fully functional AI is programmed in a binary environment as is used in current computing, would that create a bit of a black and white personality? As in just yes/no, on/off, 1/0? I will use the Skynet computer from the Terminator series as a bad analogy; it is brought online and comes to the conclusion that humanity should just be destroyed so the problem is resolved, basically its only options were; fire the missiles or not. (The films do not really go into what its moves would be after doing such a thing, but that goes into the realms of AI evolution so does not really fit with this question.) It may also have been badly programmed. Now, the human mind has been akin to a ternary system which allows our "out of the box" thinking along with all the other wonderful things our minds can do. So, would it not be more prudent to create a functional ternary system and program an AI using it so the resulting personality would be able to benefit from the third "maybe" (so to speak) option? I understand that in binary there are ways to get around the whole yes/no etc. way of things, however the basic operations are still just 1's and 0's. Again with using the above bad Skynet analogy; if it could have had that third "maybe" option as part of its core system, it may have decided to not launch due to being able to make sense of the intricacies of human nature and the politics of such a move etc. In effect, my question is; Would an AI benefit more from ternary computing as opposed to binary due to the inclusion of -1, or 2, dependent on the system ("maybe," as I call it)?

    Read the article

  • The ternary (conditional) operator in C

    - by Bongali Babu
    What is the need for the conditional operator? Functionally it is redundant, since it implements an if-else construct. If the conditional operator is more efficient than the equivalent if-else assignment, why can't if-else be interpreted more efficiently by the compiler?

    Read the article

  • Entity Relationship Model: Ternary Relationships

    - by Ethan
    Hi, I am trying to understand why this statement in the book is wrong: "given a C entity, there is at most one related A entity and at most one related B entity". Is it that it doesn't apply to a specific kind of relationship?? So, if I have an example of a student who is in attendance to a course with a type of subject. The entities are student, attendance, course and subject. Student makes attendance in a room. Also, a student can make attendance for a subject. Does this example apply to the statement? Thanks for your time.

    Read the article

  • Ternary operator in if-statement?

    - by Pindatjuh
    I've written the following if-statement in Java: if(methodName.equals("set" + this.name) || isBoolean() ? methodName.equals("is" + this.name) : methodName.equals("get" + this.name)) { ... } Is this a good practice to write such expressions in if, to separate state from condition? And can this expression be simplified?

    Read the article

  • DRY up Ruby ternary

    - by Reed G. Law
    I often have a situation where I want to do some conditional logic and then return a part of the condition. How can I do this without repeating the part of the condition in the true or false expression? For example: ClassName.method.blank? ? false : ClassName.method Is there any way to avoid repeating ClassName.method? Here is a real-world example: PROFESSIONAL_ROLES.key(self.professional_role).nil? ? 948460516 : PROFESSIONAL_ROLES.key(self.professional_role)

    Read the article

  • PHP Simplify a ternary operation

    - by Obay
    In PHP, is there a way to simplify this even more, without using an if()? $foo = $bar!==0 ? $foo : ''; I was wondering if there was a way to not reassign $foo to itself if the condition is satisfied. I understand there is a way to do this in Javascript (using &&, right?), but was wondering if there was a way to do this in PHP.

    Read the article

  • Are ternary operators not valid for linq-to-sql queries?

    - by KallDrexx
    I am trying to display a nullable date time in my JSON response. In my MVC Controller I am running the following query: var requests = (from r in _context.TestRequests where r.scheduled_time == null && r.TestRequestRuns.Count > 0 select new { id = r.id, name = r.name, start = DateAndTimeDisplayString(r.TestRequestRuns.First().start_dt), end = r.TestRequestRuns.First().end_dt.HasValue ? DateAndTimeDisplayString(r.TestRequestRuns.First().end_dt.Value) : string.Empty }); When I run requests.ToArray() I get the following exception: Could not translate expression ' Table(TestRequest) .Where(r => ((r.scheduled_time == null) AndAlso (r.TestRequestRuns.Count > 0))) .Select(r => new <>f__AnonymousType18`4(id = r.id, name = r.name, start = value(QAWebTools.Controllers.TestRequestsController). DateAndTimeDisplayString(r.TestRequestRuns.First().start_dt), end = IIF(r.TestRequestRuns.First().end_dt.HasValue, value(QAWebTools.Controllers.TestRequestsController). DateAndTimeDisplayString(r.TestRequestRuns.First().end_dt.Value), Invoke(value(System.Func`1[System.String])))))' into SQL and could not treat it as a local expression. If I comment out the end = line, everything seems to run correctly, so it doesn't seem to be the use of my local DateAndTimeDisplayString method, so the only thing I can think of is Linq to Sql doesn't like Ternary operators? I think I've used ternary operators before, but I can't remember if I did it in this code base or another code base (that uses EF4 instead of L2S). Is this true, or am I missing some other issue?

    Read the article

  • Case Insensitive Ternary Search Tree

    - by Yan Cheng CHEOK
    I had been using Ternary Search Tree for a while, as the data structure to implement a auto complete drop down combo box. Which means, when user type "fo", the drop down combo box will display foo food football The problem is, my current used of Ternary Search Tree is case sensitive. My implementation is as follow. It had been used by real world for around 1++ yeas. Hence, I consider it as quite reliable. My Ternary Search Tree code However, I am looking for a case insensitive Ternary Search Tree, which means, when I type "fo", the drop down combo box will show me foO Food fooTBall Here are some key interface for TST, where I hope the new case insentive TST may have similar interface too. /** * Stores value in the TernarySearchTree. The value may be retrieved using key. * @param key A string that indexes the object to be stored. * @param value The object to be stored in the tree. */ public void put(String key, E value) { getOrCreateNode(key).data = value; } /** * Retrieve the object indexed by key. * @param key A String index. * @return Object The object retrieved from the TernarySearchTree. */ public E get(String key) { TSTNode<E> node = getNode(key); if(node==null) return null; return node.data; } An example of usage is as follow. TSTSearchEngine is using TernarySearchTree as the core backbone. Example usage of Ternary Search Tree // There is stock named microsoft and MICROChip inside stocks ArrayList. TSTSearchEngine<Stock> engine = TSTSearchEngine<Stock>(stocks); // I wish it would return microsoft and MICROCHIP. Currently, it just return microsoft. List<Stock> results = engine.searchAll("micro");

    Read the article

  • Can I customize the indentation of ternary operators in emacs' cperl-mode?

    - by Ryan Thompson
    In emacs cperl-mode, ternary operators are not treated specially. If you break them over multiple lines, cperl-mode simply indents each line the same way it indents any continued statement, like this: $result = ($foo == $bar) ? 'result1' : ($foo == $baz) ? 'result2' : ($foo == $qux) ? 'result3' : ($foo == $quux) ? 'result4' : fail_result; This is not very readable. Is there some way that I can convince cperl-mode indent like this? $result = ($foo == $bar) ? 'result1' : ($foo == $baz) ? 'result2' : ($foo == $qux) ? 'result3' : ($foo == $quux) ? 'result4' : fail_result; By the way, code example from this question.

    Read the article

  • how to run foreach loop with ternary condition

    - by I Like PHP
    i have two foreach loop to display some data, but i want to use a single foreach on basis of database result. means if there is any row returns from database then forach($first as $fk=>$fv) should execute otherwise foreach($other as $ok) should execute. i m unsing below ternary operator which gives parse error $n=$db->numRows($taskData); // databsse results <?php ($n) ? foreach ($first as $fk=>$fv) : foreach ($other as $ok) { ?> <table><tr><td>......some data...</td></tr></table> <?php } ?> please suggest me how to handle such condition via ternary operator or any other idea. Thanks

    Read the article

  • Ternary (and n-ary) relationships in Hibernate

    - by Bytecode Ninja
    Q 1) How can we model a ternary relationship using Hibernate? For example, how can we model the ternary relationship presented here using Hibernate (or JPA)? Ideally I prefer my model to be like this: class SaleAssistant { Long id; //... } class Customer { Long id; //... } class Product { Long id; //... } class Sale { SalesAssistant soldBy; Customer buyer; Product product; //... } Q 1.1) How can we model this variation, in which each Sale item might have many Products? class SaleAssistant { Long id; //... } class Customer { Long id; //... } class Product { Long id; //... } class Sale { SalesAssistant soldBy; Customer buyer; Set<Product> products; //... } Q 2) In general, how can we model n-ary, n = 3 relationships with Hibernate? Thanks in advance.

    Read the article

1 2 3 4  | Next Page >