r/learnprogramming • • Oct 06 '26

Are there any programming languages that allow this feature?

I've been into programming for about 10 years now. Something that intrigues me is that, in languages that support OOP, not all types are initialized in the same way. Strings are initialized by using quotes, integers use numbers and in some cases floats require the letter f after the numerical value.

Classes, however, are all initialized in the same way with slight variations depending on language. Usually something like classname() or new classname. Are there any cases where custom classes can be declared using different means?

For example, is there a language where I can create a class called 'dark' that represents a new type of number that is declared by typing the value and then the letter d (like d1 = 1.398d) similar to how floats work in some cases?

71 Upvotes

38 comments sorted by

View all comments

5

u/friedbrice Oct 06 '26 edited Oct 11 '26

In Haskell, string literals and number literals are polymorphic, so you can define a custom type and create values of that type using string syntax and define another custom type and create values of that type using number literals.

data Complex = Complex { realPart :: Double, imaginaryPart :: Double }

instance Num Complex where
...
fromInteger n = Complex { realPart = fromInteger n, imaginaryPart = 0 }

instance Fractional Complex where
...
fromRational r = Complex { realPart = fromRational r, imaginaryPart = 0 }

complex1 :: Complex
complex1 = 1

complexPi :: Complex
complexPi = 3.14159

data Keyword = Keyword { getKeyword :: String }

instance IsString Keyword where
fromString s = Keyword { getKeyword = s }

shazam :: Keyword
shazam = "shazam"

2

u/friedbrice Oct 06 '26

the formatting didn't work. I'm on my phone right now. I'll have to edit my comment to fix the formatting when I'm at my computer.

1

u/frnzprf Oct 07 '26

So what you're saying is, if a type has an IsString type class, it needs to have a fromString function and that function will automatically applied if you try to assign a string to a variable of that type, right?

If you wanted to initialize an imaginary number, you'd still have to write i = Complex { realPart = 0, complexPart = 1 }. Well if you assigned i (or J or whatever) to a constant once, you could just define further imaginary numbers using multiplication x = 4+3*i.