Moved this from the Advent of Code post, as I felt it didn’t really belong there, and should be it’s own post.
I finally finished Day 5 of Advent of Code.
I have a few questions and comments that came out of the exercise.
Maybe it’s not very ‘Fortran-y’, (and definitely a lot more work than @sblionel 's elegant solution) but I created a ‘CharArray’ with push(), back(), and pop() methods to act as my stacks. It’s annoying to think that if I want to do it for a different type, I have to copy-paste everything. Hopefully generics will solve that particular issue. (I know other non-standard solutions exist, but they are still non-standard)
My implementation of pop() just decrements the size of the CharArray(). I can do this because I’m just dealing with characters. My real question is, how would I call the finalizer for the element I just popped if the element was a derived type that managed a resource? (I’m asking as if this were a generic container)
I tried to use a read statement for the io, but could not figure out the correct format string, so I implemented my own ‘split’ function instead. Are there any resources for how to write format statements? I found some that list what each character means, but I had a hard time piecing it together into a complete whole. To be honest I thought it was like a regex/pattern matching kind of thing, so I thought I could do: read(line,'("move" I "from" I "to" I)')
. Yeah, that didn’t work. I’ve only used list directed input before.
I also found an excuse to use an associate statement. It worked, but I don’t understand what it’s doing. My feeling is that it is some sort of ‘scoped macro’. Is this correct?
Elemental functions are awesome. We should do more of those. I love that I could print my final answer by doing stacks%back()
, and I was able to solve reading the “move 1 from 2 to 3” lines by splitting the line and then doing words(2::2)%to_i64()
I was able to do part 2 by modifying back(), pop(), and push() to deal with entire arrays and creating a generic type-bound procedure. It took me a long time to find the info on how to do it. I found it rather … unwieldy … to implement. But I was quite happy with the final result.
But it brought up another question for me: What actually happens when you return an allocatable array from a function and assign it to another allocatable array? As in a = return_allocatable_array()
. I know with the automatic resizing, a
will end up with the correct size and values. But does the temporary returned from the function get moved into a
or does it get copied into a
? If it’s copied, can we use move_alloc()
to avoid the copy?