I wrote a Medium article about Crystal

6 Likes

Really nice article, thank you!

Neuron 2: MACROOOOOOS!!

This was funny! I laughed :grinning_face_with_smiling_eyes:

and you cannot define a new Generic parameter at function level, just Type level

You can actually do this in Crystal: you can pass types around, and you can capture these types in type variables using forall (equivalent of that <...> thing in Kotlin, Java and C#). But maybe the documentation is a bit hidden. Here’s your example using that:

def check_type(type : T.class, value, &block : T -> _) forall T
  case value
  when T
    block.call(value)
  else
    raise "Value is not #{T}, got=#{typeof(value)}"
  end
end

check_type(Int32, 1) do |value|
  puts "Okay: #{value}"
end

check_type(Int32, "hello") do |value|
  puts "Okay: #{value}"
end

Also, if all you do with a block is just block.call, then you can use yield instead, which is a bit more idiomatic and should have slightly better performance (though it can’t be used in recursive scenarios):

def check_type(type : T.class, value, & : T -> _) forall T
  case value
  when T
    yield value
  else
    raise "Value is not #{T}, got=#{typeof(value)}"
  end
end

check_type(Int32, 1) do |value|
  puts "Okay: #{value}"
end

check_type(Int32, "hello") do |value|
  puts "Okay: #{value}"
end
2 Likes

Very nice suggestions, I’ll update my code and the article.

Thanks

1 Like

Oh, another thing, I think check_type is just the as pseudo-method

@MarioAriasC Looking forward to the performance comparison article!

VS Code has more features but isn’t consistent and crashes here and there.

Which plugin are you using? I’ve never experienced any crashes in VS code nor heard any reports of that before.

1 Like

Very nice post, thanks for sharing! While reading the following question popped out: why the original Kotlin code (and the Crystal macro’ed one) can’t be expressed with Higher-order functions (Kotlin) and procs/blocks (Crystal)? If I’m not mistaken, buildHash and buildArray both receive the same arguments and return a Collection, right?

2 Likes

Yes, I realised after someone point it on Reddit, is totally possible. But is not as fun :grinning:

I have a more compelling example of Macro usage but it was longer and required more context to comprehend, maybe in the next article I’ll include it

1 Like

Please, let me know when you publish the performance comparison article :grin: