Closed bubaflub closed 10 months ago
cons
sticks things on the front of a list. You can imagine a definition like: 'a list = nil | cons 'a ('a list)
x :: nil
in a pattern match---that's just special handling for the singleton list.You're absolutely right. I checked some other ML/OCaml examples and I was just wrong about how cons
works. I think I'll keep the code as-is for now and revisit it if it becomes too unwieldy or too slow.
Thanks!
As part of trying to parse a string IPv4 address into its binary representation, I've written a string split utility function that takes an input string
haystack
and the character to split onneedle
and returns a list of strings. I started with:And originally I wrote the helper function
stringSplit_
:But I'm getting a type-check error:
Which is surprising to me. If I reverse the order of arguments in my calls to
cons
I type check just fine but the lists are in the reverse order.stringSplit("11.2.3.4", ".")
outputs["4", "3", "2", "11"]
. I can use therev
function from one of the included examples:And then reverse the lists where appropriate:
My questions:
cons
was that it was adding an item to the end of the list. I'm guessing it actually pre-pends the item. Is that correct?stringSplit_
. This pattern matching took a while to figure out and I'm not thrilled with my solution of having both acurrent :: rest
block and acurrent :: nil
block. Is there a better (more concise, more idiomatic) way to do this pattern matching block?