Skip to content

Instantly share code, notes, and snippets.

@lee-dohm
Last active December 20, 2015 12:29
Show Gist options
  • Save lee-dohm/6131692 to your computer and use it in GitHub Desktop.
Save lee-dohm/6131692 to your computer and use it in GitHub Desktop.
Code snippets for "Adventures in Language Design" blog entry
# Explicitly opens and closes the file
def read_file1(filename)
file = nil
begin
file = File.open('somefile.txt')
return file.readlines
ensure
file.close
end
end
# Explicitly opens, but implicitly closes the
# file at the end of the block
def read_file2(filename)
File.open('somefile.txt') { |file| file.readlines }
end
def divisible_by_two(arr)
arr.select { |value| value % 2 == 0 }
end
int *divisibleByTwo(int *arr, int n)
{
int *values;
int count;
/* snip C memory allocation crap */
count = 0;
for (int i = 0; i < n; ++i)
{
if (arr[i] % 2 == 0)
{
values[count++] = arr[i];
}
}
/* snip C memory reallocation crap */
return values;
}
std::vector<int> divisibleByTwo(std::vector<int> arr)
{
std::vector<int> values(arr.size());
auto it = std::copy_if(arr.begin(),
arr.end(),
values.begin(),
[](int i){return i % 2 == 0;} );
// snip C++ memory reallocation crap
return values;
}
ERROR_CODE mungeData(size_t size,
char *inputFilename,
char *outputFilename)
{
int *bar;
CHECK_ALLOC(bar = malloc(size));
CHECK_ERR(readDataFromFile(inputFilename, bar));
CHECK_ERR(updateData(bar));
CHECK_ERR(writeDataToFile(outputFilename, bar));
free(bar):
goto success;
error:
free(bar);
return errorCode; /* Set by the CHECK_ERR macro */
success:
return SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment