Skip to content

Instantly share code, notes, and snippets.

@ion1
Last active October 22, 2018 18:52
Emulating the elegance of JavaScript's `new Array` in Haskell

Emulating the elegance of JavaScript's new Array in Haskell

What does new Array(x) do? Trick question. It does different things depending on whether x is an integer or something else.

I wanted to replicate this elegant functionality in Haskell: behold.

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, TypeApplications, TypeFamilies #-}
module EvilList where
import Data.Typeable
type family EvilList a where
EvilList Int = [()]
EvilList a = [a]
-- | Emulating the elegance of JavaScript's @new Array@.
--
-- >>> evilList (5 :: Int)
-- [(),(),(),(),()]
--
-- >>> evilList "hello"
-- ["hello"]
evilList :: forall a. (Typeable a, Typeable (EvilList a)) => a -> EvilList a
evilList a
| Just Refl <- eqT @a @Int = replicate a ()
| Just Refl <- eqT @[a] @(EvilList a) = [a]
| otherwise = undefined
@zyla
Copy link

zyla commented Oct 10, 2018

Now make it accept variable number of arguments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment