I have the following code, meant to prevent user from writing new-lines in a memo text editor:
private void m_commentMemoEdit_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData.HasFlag(Keys.Enter))
{
e.SuppressKeyPress = true;
}
}
It really does prevent Enter from being inserted, but strangely enough it prevents other keys from being inserted as well. So far we've discovered that the keys: 'O', 'M', '/' and '-' are also being "caught".
Update: The following code does what I need:
private void m_commentMemoEdit_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyValue == (int)Keys.Return)
{
e.SuppressKeyPress = true;
}
}
But I still don't understand the former code does not work and this does.
I've looked at the System.Windows.Forms.Keys enum but didn't find any clues (though I must say this is one weirdly constructed enum). Can anyone explain why is this happening?
HasFlags() is inherited from Enum.HasFlags(). It is useful on enums that are declared with the [Flags] attribute. It uses the & operator to do a test on bit values. Trouble is, Keys.Enter is not a flag value. Its value is 0x0d, 3 bits are set. So any key that has a value with bits 0, 2 or 3 turned on is going to return true. Like Keys.O, it has value 0x4f. 0x4f & 0x0d = 0x0d so HasFlags() returns true.
You should only use it with Keys values that actually represent flag values. They are Keys.Alt, Keys.Control and Keys.Shift. Note that these are modifier keys. So you can use HasFlags to see the difference between, say, F and Ctrl+F.
To detect Keys.Enter you should do a simple comparison. As you found out. Note that your if() statement is also true for Alt+Enter, etcetera, this might not be what you want. Instead use
if (e.KeyData == Keys.Return) e.SuppressKeyPress = true;
Which suppresses the Enter key only if none of the modifier keys are pressed.
I suspect it has something to do with the underlying values of the System.Windows.Forms.Keys enum being mapped directly to the keyboard codes, which are not always mutually exclusive. The documentation says that you should not use any kind of bitwise operation on them, and gives an example of why not (Beware the FlagsAttribute on the enum!).
MSDN also says that the HasFlag function returns the result of this: thisInstance And flag = flag, so you could potentially set a breakpoint and look at the actual binary codes coming in and see if that operation would give you a true for the set of keys you listed.
In the end, your updated code is the right way to do what you want to do.
HasFlag is for Flags - which means if a bit is set or not
the keyvalue is an ordinal value, so completely different from flags
use the comparison operator and everything should be fine.
some enum fields are defined like flags, e.g.
enum SomeFlag
{
BitOne = 1,
BitTwo = 2,
Bitthree = 4
};
here it makes sense to use "HasFlag"
I have a decision tree of height 2:
const BOOL isVerticalAnimationRequired = YES;
const BOOL isArgumentEditorExpanded = YES;
const BOOL isSelectionLeftToRight = YES;
UITableViewRowAnimation argumentEditorAnimation;
if (isVerticalAnimationRequired)
{
argumentEditorAnimation = (isArgumentEditorExpanded) ? UITableViewRowAnimationTop : UITableViewRowAnimationBottom;
}
else
{
argumentEditorAnimation = (isSelectionLeftToRight) ? UITableViewRowAnimationLeft : UITableViewRowAnimationRight;
}
My problem is that the code is verbose. Ideally I would like to declare and set argumentEditorAnimation in one statement.
Are there any clever C style tips for handling situation like this?
I think I would not try to fold this into one expression for reasons of clarity, but if you must:
argumentEditorAnimation =
isVerticalAnimationRequired ?
(isArgumentEditorExpanded ?
UITableViewRowAnimationTop
: UITableViewRowAnimationBottom)
: (isSelectionLeftToRight ?
UITableViewRowAnimationLeft
: UITableViewRowAnimationRight);
Alternatively, you can make your code more concise by dropping the {} when they're not needed.
(Consider using shorter identifiers if you want to write these kinds of expressions. The long identifiers make the code verbose as well. E.g., drop the is in your booleans.)
Sometimes logic like this can best be expressed with a small table that you index with your decision criteria.
In this case, I would just use good formatting as larsmans showed in his answer.
I am trying loop over an array and return a value as shown below. But this gives me an error on the line after the if statement. It says "This expression was expected to have type unit but has type int"
let findMostSignificantBitPosition (inputBits:System.Collections.BitArray) =
for i = inputBits.Length - 1 to 0 do
if inputBits.[i] then
i
done
How would I do this? I am in the middle of recoding this with a recursive loop, as it seems to be the more accepted way of doing such loops in functional languages, but I still want to know what I was doing wrong above.
for loops are not supposed to return values, they only do an operation a fixed number of times then return () (unit). If you want to iterate and finally return something, you may :
have outside the loop a reference where you put the final result when you get it, then after the loop return the reference content
use a recursive function directly
use a higher-order function that will encapsulate the traversal for you, and let you concentrate on the application logic
The higher-function is nice if your data structure supports it. Simple traversal functions such as fold_left, however, don't support stopping the iteration prematurely. If you wish to support this (and clearly it would be interesting in your use case), you must use a traversal with premature exit support. For easy functions such as yours, a simple recursive function is probably the simplest.
In F# it should also be possible to write your function in imperative style, using yield to turn it into a generator, then finally forcing the generator to get the result. This could be seen as a counterpart of the OCaml technique of using an exception to jump out of the loop.
Edit: A nice solution to avoid the "premature stop" questions is to use a lazy intermediate data structure, which will only be built up to the first satisfying result. This is elegant and good scripting style, but still less efficient than direct exit support or simple recursion. I guess it depends on your needs; is this function to be used in a critical path?
Edit: following are some code sample. They're OCaml and the data structures are different (some of them use libraries from Batteries), but the ideas are the same.
(* using a reference as accumulator *)
let most_significant_bit input_bits =
let result = ref None in
for i = Array.length input_bits - 1 downto 0 do
if input_bits.(i) then
if !result = None then
result := Some i
done;
!result
let most_significant_bit input_bits =
let result = ref None in
for i = 0 to Array.length input_bits - 1 do
if input_bits.(i) then
(* only the last one will be kept *)
result := Some i
done;
!result
(* simple recursive version *)
let most_significant_bit input_bits =
let rec loop = function
| -1 -> None
| i ->
if input_bits.(i) then Some i
else loop (i - 1)
in
loop (Array.length input_bits - 1)
(* higher-order traversal *)
open Batteries_uni
let most_significant_bit input_bits =
Array.fold_lefti
(fun result i ->
if input_bits.(i) && result = None then Some i else result)
None input_bits
(* traversal using an intermediate lazy data structure
(a --- b) is the decreasing enumeration of integers in [b; a] *)
open Batteries_uni
let most_significant_bit input_bits =
(Array.length input_bits - 1) --- 0
|> Enum.Exceptionless.find (fun i -> input_bits.(i))
(* using an exception to break out of the loop; if I understand
correctly, exceptions are rather discouraged in F# for efficiency
reasons. I proposed to use `yield` instead and then force the
generator, but this has no direct OCaml equivalent. *)
exception Result of int
let most_significant_bit input_bits =
try
for i = Array.length input_bits - 1 downto 0 do
if input_bits.(i) then raise (Result i)
done;
None
with Result i -> Some i
Why using a loop when you can use high-order functions?
I would write:
let findMostSignificantBitPosition (inputBits:System.Collections.BitArray) =
Seq.cast<bool> inputBits |> Seq.tryFindIndex id
Seq module contains many functions for manipulating collections. It is often a good alternative to using imperative loops.
but I still want to know what I was
doing wrong above.
The body of a for loop is an expression of type unit. The only thing you can do from there is doing side-effects (modifying a mutable value, printing...).
In F#, a if then else is similar to ? : from C languages. The then and the else parts must have the same type, otherwise it doesn't make sense in a language with static typing. When the else is missing, the compiler assumes it is else (). Thus, the then must have type unit. Putting a value in a for loop doesn't mean return, because everything is a value in F# (including a if then).
+1 for gasche
Here are some examples in F#. I added one (the second) to show how yield works with for within a sequence expression, as gasche mentioned.
(* using a mutable variable as accumulator as per gasche's example *)
let findMostSignificantBitPosition (inputBits: BitArray) =
let mutable ret = None // 0
for i = inputBits.Length - 1 downto 0 do
if inputBits.[i] then ret <- i
ret
(* transforming to a Seq of integers with a for, then taking the first element *)
let findMostSignificantBitPosition2 (inputBits: BitArray) =
seq {
for i = 0 to inputBits.Length - 1 do
if inputBits.[i] then yield i
} |> Seq.head
(* casting to a sequence of bools then taking the index of the first "true" *)
let findMostSignificantBitPosition3 (inputBits: BitArray) =
inputBits|> Seq.cast<bool> |> Seq.findIndex(fun f -> f)
Edit: versions returning an Option
let findMostSignificantBitPosition (inputBits: BitArray) =
let mutable ret = None
for i = inputBits.Length - 1 downto 0 do
if inputBits.[i] then ret <- Some i
ret
let findMostSignificantBitPosition2 (inputBits: BitArray) =
seq {
for i = 0 to inputBits.Length - 1 do
if inputBits.[i] then yield Some(i)
else yield None
} |> Seq.tryPick id
let findMostSignificantBitPosition3 (inputBits: BitArray) =
inputBits|> Seq.cast<bool> |> Seq.tryFindIndex(fun f -> f)
I would recommend using a higher-order function (as mentioned by Laurent) or writing a recursive function explicitly (which is a general approach to replace loops in F#).
If you want to see some fancy F# solution (which is probably better version of using some temporary lazy data structure), then you can take a look at my article which defines imperative computation builder for F#. This allows you to write something like:
let findMostSignificantBitPosition (inputBits:BitArray) = imperative {
for b in Seq.cast<bool> inputBits do
if b then return true
return false }
There is some overhead (as with using other temporary lazy data structures), but it looks just like C# :-).
EDIT I also posted the samples on F# Snippets: http://fssnip.net/40
I think the reason your having issues with how to write this code is that you're not handling the failure case of not finding a set bit. Others have posted many ways of finding the bit. Here are a few ways of handling the failure case.
failure case by Option
let findMostSignificantBitPosition (inputBits:System.Collections.BitArray) =
let rec loop i =
if i = -1 then
None
elif inputBits.[i] then
Some i
else
loop (i - 1)
loop (inputBits.Length - 1)
let test = new BitArray(1)
match findMostSignificantBitPosition test with
| Some i -> printf "Most Significant Bit: %i" i
| None -> printf "Most Significant Bit Not Found"
failure case by Exception
let findMostSignificantBitPosition (inputBits:System.Collections.BitArray) =
let rec loop i =
if i = -1 then
failwith "Most Significant Bit Not Found"
elif inputBits.[i] then
i
else
loop (i - 1)
loop (inputBits.Length - 1)
let test = new BitArray(1)
try
let i = findMostSignificantBitPosition test
printf "Most Significant Bit: %i" i
with
| Failure msg -> printf "%s" msg
failure case by -1
let findMostSignificantBitPosition (inputBits:System.Collections.BitArray) =
let rec loop i =
if i = -1 then
i
elif inputBits.[i] then
i
else
loop (i - 1)
loop (inputBits.Length - 1)
let test = new BitArray(1)
let i = findMostSignificantBitPosition test
if i <> -1 then
printf "Most Significant Bit: %i" i
else
printf "Most Significant Bit Not Found"
One of the options is to use seq and findIndex method as:
let findMostSignificantBitPosition (inputBits:System.Collections.BitArray) =
seq {
for i = inputBits.Length - 1 to 0 do
yield inputBits.[i]
} |> Seq.findIndex(fun e -> e)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm just curious what peoples' thoughts are on this topic. Let's say I have an Array of Objects, and I want to loop through them to see if the Objects contain certain values, and if so, I want to stop the loop. Which is better practice - a for loop with a break, or a conditional loop?
The pseudo-code in the example I have provided is for argument's sake only (it is also in ActionScript, since that is my primary language of late). Also, I am not looking for best practice ideas on syntax.
for loop with break:
var i:int;
var isBaxterInMilwaukee:Boolean;
for (i = 0; i < arrayLen; i++)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
break;
}
}
conditional loop:
var i:int;
var isBaxterInMilwaukee:Boolean;
while (!isBaxterInMilwaukee && i < arrayLen)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
i++;
}
In short, you should go with whichever version is the easiest to read and maintain.
In slightly older times, I know breaking out of a loop was considered to be a no-no (on par with a goto statement). Loops were supposed to break on the loop condition and nowhere else. Thus, the while-loop would have been the way to go.
(This is probably a holdover from assembly, where loops are basically a block of code with a go-to-the-beginning-if-true jump statement at the end. Multiple conditional-jump statements in the block make it exceedingly hard to debug; thus they were to be avoided and combined into one at the end.)
I feel this idea seems to be changing a bit today, especially with foreach loops and the managed world; it's really a matter of style now. Break-on-found for-loops have perhaps come to be acceptable to many, save some purists of course. Note that I would still avoid using break in a while-loop, however, as this can muddle the loop condition and make it confusing.
If you'll allow me to use a foreach loop, I consider the code below to be a lot easier to read than its while-loop brother:
bool isBaxterInMilwaukee;
foreach (var item in myArray)
{
if (item.name == "baxter" && item.location == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
break;
}
}
However, as the logic grows in complexity, you may want to consider a prominent comment near the break statement lest it become buried and hard to find.
Arguably, this whole thing should be refactored into its own function which doesn't break on found, but actually returns the result (feel free to use the for-loop version instead):
bool isBaxterInMilwaukee(Array myArray)
{
foreach (var item in myArray)
{
if (item.name == "baxter" && item.location == "milwaukee")
{
barkTwice();
return true;
}
}
return false;
}
As Esko Luontola pointed out, it would probably be best to move the call to barkTwice() outside of this function as the side-effect is not evident from the function's name, nor related to finding Baxter in every case. (Or add a boolean parameter BarkTwiceIfFound and change the line to read if(BarkTwiceIfFound) barkTwice(); to make the side-effect clear.)
For the record, you can also do the flag check in the for-loop without a break, but I feel this actually hurts readability because you don't expect an extra condition in a for-loop definition:
var i:int;
var isBaxterInMilwaukee:Boolean;
for (i = 0; !isBaxterInMilwaukee && i < arrayLen; i++)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
}
You can also simulate auto-incrementing mechanics with a while-loop. I don't like this for a few reasons - you have to initialize i to be one less than your real starting value, and depending on how your compiler short-circuits the loop-condition logic, your value of i on exiting the loop may vary. Nevertheless, it is possible and for some people, this can improve readability:
var i:int = -1;
var isBaxterInMilwaukee:Boolean;
while (!isBaxterInMilwaukee && ++i < arrayLen)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
}
I've always disliked the use of breaks in code... In this case it doesn't seem to matter but on more involved loops, it can be awfully confusing to another coder reading it. In general, it often results in not understanding how the loop may terminate until the coder spots the nested break deep in the loop. By specifying a flag condition that's checked each iteration of the loop, it makes this much clearer.
This problem would be similar to having return statements that are deep in the body of a method where they're not easily spotted (rather than setting a retVal variable and returning at the end of the method). With a small method, this seems fine, but the bigger it gets, the more confusing this will be.
It's not an efficiency of operation thing, it's a maintainability thing.
Ask your coworkers what's readable and understandable for a particular situation... That's what really matters.
I would say it depends. In this case the loop with the break seems clearer to me.
In a for loop you can also early exit by putting the early exit criteria in the for loop declaration. So for your example you could do it this way:
var i:int;
var isBaxterInMilwaukee:Boolean;
isBaxterInMilwaukee = false;
for (i = 0; i < arrayLen && !isBaxterInMilwaukee; i++)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
}
That way you don't need a break, and it's still more readable than a while loop.
There is a conceptual difference between the two. for loops are for iterating over discrete sets and while loops are for repeating statements based on a condition. Other languages add in finally clauses and looping constructs like foreach or until. They tend to have considerably fewer traditional for loops.
In any case, the rule that I use is that for loops iterate and while loops repeat. If you see something like:
while (counter <= end) {
// do really cool stuff
++counter;
}
Then you are probably better off with a for loop since you are iterating. However, loops like:
for (int tryCount=0; tryCount<2; ++tryCount) {
if (someOperation() == SUCCESS) {
break;
}
}
should be written as while loops since they are really repeating something until a condition is true.
The thought of not using break since it is just as evil as goto is pretty nonsensical. How can you justify throwing an exception then? That's just a non-local and non-deterministic goto! By the way, this isn't a rant against exception handling, just an observation.
The one that makes the most sense is going to be the one that conveys the idea to the human reading the code the best. Remember code readability first, and you'll usually make the correct choice. Usually, you do not want to use something like break unless you really need to, because it can make things hard to follow if done often or even just in a deeply-nested set of expressions. continue can serve the same purpose as a break sometimes, and the loop will then exit normally instead of because it was broken. In this case, there are a couple of different ways I might write this.
Probably the best thing you want here is a modification of your while loop:
while(!isBaxterInMilwaukee || i < arrayLen) {
if(myArray[i]["name"] == "baxter" && myArray[i]["location"] == "milwaukee") {
isBaxterInMilwaukee == true;
barkTwice()
} else {
i++;
}
}
That's clear and doesn't use break or continue, so you can tell at a glance that you'll always terminate as a result of one of the conditions specified in the while expression.
ETA: Probably should be i < arrayLen in the while loop otherwise it fails the first time through unless the input value is the same as the target value...
I see the break in both loops, is that correct?
Anyway:
I would choose FOR loop when there is known number (maximum number) of iterations before loop starts.
I would choose WHILE otherwise.
In FOR loop I use BREAK freely.
In WHILE loop I prefer to use complex condition instead of BREAK (if it is possible).
I would say break, clearer (even if you put in a comment why you break out of the loop)
Imho the while loop is not clear, i would go for break
I would definitely go with the for+break. The ‘for’ is an instantly-recognisable idiom for “iterate over sequence” and it's easier to understand “iterate over sequence; end early if value found” than the combined loop-and-stop condition.
There may be evidence for this in the way you seem to have made two mistakes in your conditional loop code!
the while condition (!isBaxterInMilwaukee || i == arrayLen) — did you mean “(!(isBaxterInMilwaukee || i == arrayLen))”?
break statement is unnecessary if you're using a terminate-loop variable.
Personally I find a simple ‘break’ much easier to read than trying to track a terminate-loop variable.
There are two aspects of the problem:
What to do (eg: find if one of the items contain the specified person in the location)
How to do it (eg: use an index, iterate etc)
Both of the examples mix the two and is hard to understand the what from the how. The best would be if we could express in code only the what part. Here is an example (c# 3.5) that does this using the specification pattern
// what we are looking for?
IsPersonInLocation condition = new IsPersonInLocation("baxter", "milwaukee");
// does the array contain what we are looking for?
bool found = myArray.Find(item => condition.IsSatifiedBy(item));
// do something if the condition is satisfied
if (found) {
barkTwice();
}
For completeness here is the class definition for the condition:
class IsPersonInLocation {
public string Person { get; set; }
public string Location { get; set; }
public IsPersonInLocation(string person, string location) {
this.Person = person;
this.Location = location;
}
bool IsSatifiedBy(item) {
return item["name"] == this.Person
&& item["location"] == this.Location;
}
}
It depends a lot on what the specific circumstances are. But in your example, you want to walk an array of bounded length, and using a for loop makes it easy to do that and guard against running off the end. In your while loop example you have to do your own incrementing--which can be problematic if you wanted to use a continue statement to skip into the next cycle--and make a more complex conditional expression (which, by the way, has a bug; I think you meant && i != arrayLen ). You're just having to do extra code to accomplish the effect that for loops help provide.
Of course, some purists will argue that break and continue should not be used and that you should use if-else and boolean variables if needed rather than continue or break out of a loop. But I think that can make the loop look much more ugly, especially if its relatively short and easy to grasp in general like this example. For a loop with much longer code where a break or continue could easily hide from notice, the purist approach might be more clear, since the loop is already complicated to grasp in that case. But you can always do this as part of the for loop, just add it as part of the conditional.
It's also better practice to test the array bound with i < arrayLen rather than for an exact equality, in case something caused i to skip over the exact value (I actually saw this happen in a Y2K bug, which could have been avoided by the better practice).
I have a C++ background and so I still have moments where I try to "think like the compiler". While loops tend to result in tighter code, and so for loops were only ever considered if you knew you were going to iterate over every element in the array, every time.
EDIT: I now believe this is overkill, if you're using .Net or whatever you aren't going to make up for the VM overhead with a couple of tight loops. I do think remembering the "why" of certain practices is a good thing though.
My theory is that there is a useful programming abstraction similar to "signal-to-noise ratio", which is "problem-to-tool ratio" - goodness can be measured in one dimension by how much time I spend thinking about the problem and its solution, compared to the time I spend thinking about how to use the tool (in this case language syntax).
By that measure, I try to use fewer constructs more frequently, because I (and hopefully those who follow) can grok the essence of my code structure more quickly and accurately. And since variations of "for loops" do a pretty good job of covering the cases where the others might be used (without distortion), I use them as a first preference, when they are interchangeable.
And it's nice to have everything you need to know (grokwise) about the loops rules in a single line at the top of the "for" loop. I also tend to put the "default" switch first in the tests for the same reason.
But consistency and clarity is the ovveriding consideration. YMMV, of course.
I guess neither is actually vary interesting. You should look for higher level constructs if it's readability you're after.
In JS:
if(myArray.some(function(o) { o.name == "baxter" && o.location == "milwaukee" }))
barkTwice();
or with some utils of your own
if(myArray.containsMatch({name:"baxter",location:"milwaukee"})
barkTwice();
Encapsulate the loop in its own method and use return to end processing when your match condition has succeeded.
Some example C# code:
class Program
{
static bool IsBaxterInMilwaukee(IList<WhoAndWhere> peopleAndPlaces)
{
foreach (WhoAndWhere personAndPlace in peopleAndPlaces)
{
if (personAndPlace.Name == "Baxter"
&& personAndPlace.Location == "Milwaukee")
{
return true;
}
}
return false;
}
static void Main(string[] args)
{
List<WhoAndWhere> somePeopleAndPlaces = new List<WhoAndWhere>();
somePeopleAndPlaces.Add(new WhoAndWhere("Fred", "Vancouver"));
somePeopleAndPlaces.Add(new WhoAndWhere("Baxter", "Milwaukee"));
somePeopleAndPlaces.Add(new WhoAndWhere("George", "London"));
if (IsBaxterInMilwaukee(somePeopleAndPlaces))
{
// BarkTwice()
Console.WriteLine("Bark twice");
}
}
public class WhoAndWhere
{
public WhoAndWhere(string name, string location)
{
this.Name = name;
this.Location = location;
}
public string Name { get; private set; }
public string Location { get; private set; }
}
}
My general stance is:
If it has a loop counter use for() (like while while loop does).
I vote while because breaks reduce grokability.
You may not realize the loop contains a break if the loop has grown too long and you insert code you expect to run and it does not.
But I subscribe to the don't make me think model of coding.
In ES6, it has been made very easy, no need to use the break keyword, We can use the find function, once the condition satisfies, we can return true.
let barkTwice = () => {
console.log('bark twice');
}
let arr = [{
location: "waukee",
name: "ter"
}, {
location: "milwaukee",
name: "baxter"
},
{
location: "sample",
name: "sampename"
}
];
Here we matching the condition and once the condition matches, we are calling the function, as per the question and then we are returning true. So that it does not go beyond.
arr.find(item => {
if (item.location == "milwaukee" && item.name == "baxter") {
barkTwice();
return true
}
});