Posted on January 24, 2014
by Kwang Yul Seo
Tags: Haskell, string literal
In writing a compiler or an interpreter, it is common to define a symbol or identifier type which is distinct from String to make it more type-safe.
newtype Symbol = Symbol StringNow String and Symbol are distinct types and we can’t accidentally mix two. But it also means that we have to use Symbol constructor whenever we need to create a symbol from a string literal.
Symbol "main"You can avoid this labor using the GHC extension, OverloadedStrings. By making Symbol an instance of IsString, GHC automatically coerces a string literal into a symbol.
{-# LANGUAGE OverloadedStrings #-}
import Data.String
instance IsString Symbol where
fromString = Symbol . fromString
s :: Symbol
s = "hello"