In haskell you can do this:
type Parser a = String -> [(a, String)]
I tried to make something similar in Swift. So far I wrote these codes with no luck.
typealias Parser<A> = String -> [(A, String)] typealias Parser a = String -> [(a, String)] typealias Parser = String -> [(A, String)]
So is this simply impossible in swift? And if it is is there another ways to implement this behavior?
UPDATE: It seems generic typealiases are now supported in swift 3 https://github.com/apple/swift/blob/master/CHANGELOG.md
Swift Generics allows us to create a single function and class (or any other types) that can be used with different data types. This helps us to reuse our code.
A type alias allows you to provide a new name for an existing data type into your program. After a type alias is declared, the aliased name can be used instead of the existing type throughout the program. Type alias do not create new types. They simply provide a new name to an existing type.
Declaring a typealias A typealias can be declared in Swift using the typealias keyword followed by the type you want to assign. A very simple example to understand how they can be used is by making an alias for currency, like Dollars.
Generics and Any are often used for similar purposes, yet they behave very differently. In languages without generics, you typically use a combination of Any and runtime programming, whereas generics are statically checked at compile time.
In addition to generic functions, Swift enables you to define your own generic types. These are custom classes, structures, and enumerations that can work with any type, in a similar way to Array and Dictionary. This section shows you how to write a generic collection type called Stack.
Here, typealias is a keyword, dataType is one of primitive, user-defined, or complex data type, and myAlias is an alias to dataType i.e, now we can call datatype with the name myDataType. In Swift, broadly we can define an alias for the following data types: 1. Type alias for primitive data types
In Swift, you can use typealias for most types. They can be either: Built-in types (for.eg: String, Int) User-defined types (for.e.g: class, struct, enum) Complex types (for e.g: closures)
It is declared using the keyword typealias as: In Swift, you can use typealias for most types. They can be either: You can use typealias for all built in data Types as String, Int, Float etc.
Generic typealias
can be used since Swift 3.0. This should work for you:
typealias Parser<A> = (String) -> [(A, String)]
Here is the full documentation: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/swift/grammar/typealias-declaration
Usage (from @Calin Drule comment):
func parse<A>(stringToParse: String, parser: Parser)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With