Home > Blockchain >  Lambda function typing in Dart?
Lambda function typing in Dart?

Time:06-21

Basically, I try to duplicate the way to type functions in Haskell.

myIdentity :: a -> a  -- type only
myIdentity = \a -> a

In TypeScript, I found we can do like this,

type identity = <A>(a: A) => A; // type only
const identity: identity = a => a;

In Dart, so far I know we can write as follows

var identity = (a) => a;

or

A identity<A>(A a) => a;

Can we also express function type like Haskell/TypeScript style?

EDIT:

basically, I want to write separately in 2 lines

  1. a type definition alone for a function such as "blueprint" of the function.

  2. with the type definition, the actual implementation of the function

EDIT2:

typedef IdSpecific<T> = T Function(T);
IdSpecific id = (x) => x;

void main(List<String> arguments) {
  print('Hello world: ${id(5)}!');
  print('Hello world: ${id("Five")}!');
}

the result:

Hello world: 5!
Hello world: Five!

CodePudding user response:

You can write the generic function directly as:

var identity = <T>(T x) => x;

You can give it a type, like in TypeScript, by:

typedef IdAny = T Function<T>(T);
IdAny identity = <T>(T x) => x;

or write the function type directly as:

T Function<T>(T) identity = <T>(T x) => x;

Here the identity function is a generic function. You can specialize it as var intId = identity<int>; var stringId = identity<String>; if you want to.

Notice that this is not the same as:

typdef IdSpecific<T> = T Function(T);
IdSpecific id2 = (x) => x;

In this latter case, the function is not generic. Instead the type alias is generic, but it is instantiated (to its bound dynamic) when used to type id2, which therefore has type IdSpecific<dynamic>, aka. dynamic Function(dynamic), and its value is (dynamic x) => x.

CodePudding user response:

typedef Identity<A> = A Function(A);
Identity identity = (a) => a;

Self answer, but the credit goes to @jamesddin.

Thank you!

  •  Tags:  
  • dart
  • Related