I want to take the transpose of a matrix using only higher order functions in sml,but I am really stack

StackOverflow https://stackoverflow.com/questions/19500459

  •  01-07-2022
  •  | 
  •  

Вопрос

I want to take the transpose of a matrix using only higher order functions in sml,but I am really stack,here is what i have

fun transpose [] = []
| transpose ([]::_) = []
| transpose mat = (map hd mat)::(transpose(map tl mat));

but I dont want to call transpose because recursion is again not allowed.I also want to get rid of cases.Any help?

Это было полезно?

Решение

transpose mat = tabulate (length (nth (mat,0)),fn i => map (fn l => (nth (l,i))) mat)

Or, for more readability and safety on empty matrices:

transpose mat =
  let
    val rows = length mat
    val cols = if rows > 0
               then length (nth (mat,0))
               else 0
  in
    tabulate (cols, fn i => map (fn row => (nth (row, i)) mat)
  end
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top