How to define an alias type?

30 Views Asked by At

A route is defined as a [String, String] tuple. What is the most appropriate way to define type alias 'Route' as [String, String]? e.g.

defn same-route? ( x : [String,String], y : [String,String] ) -> True|False :

I would like to use

defn same-route? ( x : Route, y : Route ) -> True|False :

instead.

1

There are 1 best solutions below

0
On

The standard way would be to define a Route struct that wraps the Strings:

defstruct Route :
  start: String
  end: String

Inside same-route? you can compare the start and end fields.

defn same-route? (x:Route, y:Route) -> True|False :
  start(x) == start(y) and end(x) == end(y)

The preferred way to compare equality is to subtype Equalable and implement the equal? method:

defstruct Route <: Equalable :
  start: String
  end: String

defmethod equal? (x:Route, y:Route) -> True|False :
  start(x) == start(y) and end(x) == end(y)

== is a macro for equal?, so this enables the following code:

val x = Route("San Francisco", "Madrid")
val y = Route("Paris", "New Delhi")
println(x == y)
> false