Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a type that is a subset of an other type

Tags:

types

haskell

How can you create a type that is a subset of an other type? I want a string type that only contains alphanumeric characters.

So I want something like this

type AlphNumString = [AlphaNumChar]
data AlphaNumChar = ???? filter (isAlphaNum) Char ????
like image 700
Henk Avatar asked Oct 24 '15 15:10

Henk


People also ask

How do you create a type?

Use the CREATE TYPE statement to create the specification of an object type, a SQLJ object type, a named varying array (varray), a nested table type, or an incomplete object type. You create object types with the CREATE TYPE and the CREATE TYPE BODY statements.

What does ?: Mean in TypeScript?

What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .

What is ReturnType TypeScript?

The ReturnType in TypeScript is a utility type which is quite similar to the Parameters Type. It let's you take the return output of a function, and construct a type based off it.


2 Answers

The standard way to do this is with so-called "smart constructors".

First, you define a new type that's identical to the old one:

newtype AlphNumString = X String

Next, you write the smart constructor itself:

toAlphNumString :: String -> AlphNumString
toAlphNumString txt = X (filter isAlphNum txt)

Finally, you make it so toAlphNumString is the only way to create an AlphNumString.

module Foo (AlphNumString (), toAlphNumString, ...) where ...

Note that this does not allow you to use an AlphNumString like a normal String; you can't create "subtypes" like that in Haskell. So you'll also need another function

fromAlphNumString :: AlphNumString -> String
fromAlphNumString (X txt) = txt
like image 179
MathematicalOrchid Avatar answered Oct 17 '22 22:10

MathematicalOrchid


This concept of types that are "subsets" of other types based on some predicate is called refinement types. For Haskell, this is implemented as LiquidHaskell.

However, I would consider this an ongoing research. In practice, I would go with a newtype and dynamic checks, as MathematicalOrchid describes in their answer.

like image 27
Roman Cheplyaka Avatar answered Oct 17 '22 21:10

Roman Cheplyaka