Skip to content

Instantly share code, notes, and snippets.

@ion1
Last active October 22, 2018 18:52
Show Gist options
  • Save ion1/254dec8391631a25da836b5b7d7164fe to your computer and use it in GitHub Desktop.
Save ion1/254dec8391631a25da836b5b7d7164fe to your computer and use it in GitHub Desktop.
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
@Cypher1
Copy link

Cypher1 commented Oct 7, 2018

Why have you done this?

@jflanglois
Copy link

:(

@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