Вопрос

I need to create a method that takes a list of lists (like [ [2,3,] , [4,5] ]) and returns something like [2,3,4,5]. I can work out the logic but I dont know how to define the method in SML. I tried this but it does not compile

    fun appendall(l:list list):list = ...
Это было полезно?

Решение

Looks like you've just got your types wrong. A list has to be a list of something (e.g. an int list). If the type of the contents is irrelevant, you can use a type variable 'a instead of a concrete type (so in your case, an 'a list and an 'a list list).

However, you almost never need type declarations in ML. Just write your function without them, and the compiler will be able to infer the types of the variables from the operations you're performing on them.

Другие советы

Take a look at the concat function from the List libary.

Moscow ML version 2.01 (January 2004)
Enter `quit();' to quit.
- load "List";
> val it = () : unit
- List.concat [[1,2],[3,4],[5,6]];
> val it = [1, 2, 3, 4, 5, 6] : int list
- quit();

An alternative solution could be to use List.foldr

val concat = List.foldr op@ [];

Or you could just write it plain as an recursive function

fun concat2 [] = []
  | concat2 (x::xs) = x @ concat2 xs

Hope this helps you.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top