Hacker News new | ask | show | jobs
by cdoxsey 4291 days ago
In my experience solutions generally fall into two camps:

1) Create a "generic" version of the function using reflection / typecasts 2) Create a specific version of the function for your use-case

I don't have a ton of experience using channels. My code tends to be very imperative and I add the channel layer at the main application level rather than the library level.

So from his example:

> func merge[T](cs ...<-chan T) <-chan T

You can create a function:

   func merge(cs ...interface{}) interface{}
Then call it:

   merged := merge(c1, c2, c3).(<-chan int)
You lose type safety and pay some penalty for performance. Also merge is harder to write than it would be with generics.

But even languages with generics often have similar issues. For example you can't write a generic min/max in C# either.

1 comments

You can in Haskell

    min :: Ord a => [a] -> Maybe a
    min = foldl' go Nothing where
      go Nothing a  = Just a
      go a0@(Just m) a 
        | a < m     = Just a
        | otherwise = a0
You can in OCaml

    module Min (M : Comparable.S) : sig
        val min : M.t list -> M.t option
      end = struct
        open M
        let go a0 a = match a0 with
            None    -> Some(a)
          | Some(m) -> if a < m then Some(a) else a0
        let min l = List.fold_left go None l
      end
Point being that these problems with generics are reasonably solved. There are perhaps other problems, of course. OCaml should at least be a suggestion that compilation speed isn't really one of them.