Skip to content

Instantly share code, notes, and snippets.

@ReedCopsey
Last active December 20, 2019 03:17
Show Gist options
  • Save ReedCopsey/4813b05b77d180cebaa71609289351c8 to your computer and use it in GitHub Desktop.
Save ReedCopsey/4813b05b77d180cebaa71609289351c8 to your computer and use it in GitHub Desktop.
F# Looping Sample Code
int sum = 0;
for (int number = 1; number < 21; number++)
{
if (number % 3 == 0)
{
sum = sum + number;
}
}
Console.WriteLine($"The sum is {sum}");
int AddNewConditionally(int last, int number)
{
if(number % 3 == 0)
return last + number;
else
return last;
}
int sum = 0;
for (int number = 1; number < 21; number++)
{
sum = AddNewConditionally(sum, number);
}
Console.WriteLine($"The sum is {sum}");
foreach (var number in Enumerable.Range(1,20))
{
sum = AddNewConditionally(sum, number);
}
let addNewConditionally last number =
if number % 3 = 0 then last + number else last
// Start with "0"
let startingValue = 0
let valuesToProcess = { 1 .. 20 }
// Fold instead of looping
let sum = Seq.fold addNewConditionally startingValue valuesToProcess
printfn "The sum is %d" sum
let addNewConditionally last number =
if number % 3 = 0 then last + number else last
let sum = { 1 .. 20 } |> Seq.fold addNewConditionally 0
printfn "The sum is %d" sum
let buildListConditionally l number =
if number % 3 = 0 then (string number)::l else l
let values = { 1 .. 20 } |> Seq.fold buildListConditionally []
printfn "The values are %A" values
printfn "The first value is \"%s\"" (List.head values)
let addNewConditionally last number =
if number % 3 = 0 then last + number else last
// Start with "0"
let startingValue = 0
let valuesToProcess = { 1 .. 20 }
// Make a value we can increment as we loop
let mutable runningValue = startingValue
for number in valuesToProcess do
// Adjust this each step
runningValue <- addNewConditionally runningValue number
// Get the result at the end
let sum = runningValue
printfn "The sum is %d" sum
let addNewConditionally last number =
if number % 3 = 0 then last + number else last
let mutable sum = 0
for number in { 1..20 } do
sum <- addNewConditionally sum number
printfn "The sum is %d" sum
Seq.fold : ('State -> 'T -> 'State) -> 'State -> seq<'T> -> 'State
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment