First matrix column defined as a list of rows in Haskell

If I have a matrix defined as a list of rows [[1,2,3], [4,5,6]], I want to return the first column, [1,4]. I am an absolute newbie to Haskell and I don’t even know how to work with nested lists.

+3
source share
4 answers

The following code will complete the task:

map head [[1,2,3],[4,5,6]]

mapis one of the most useful features in haskell (and other functional programming languages). Given a list [a,b,c,d]and function f, map f [a,b,c,d]will return a list [f a, f b, f c, f d]. The function headretrieves the first element of the list. That's why

map head [[1,2,3],[4,5,6]] ->
[head [1,2,3], head [4,5,6]] ->
[1,4]
+6
source

In a more general form:

col :: Int -> [[a]] -> [a]
col n = map (head . drop n)

, , n , .

+6

Data.List.transpose. , -

import Data.List (transpose)
col = head . transpose

:

colN n matrix = transpose matrix !! n

:

, , . , , .

, , , : [[a]] -> [[a]]. . ( .)

+2

:

map head [[1,2,3],[4,5,6]]

; map . "" .

, , [[Int]], , Int s. , , ; head.

, map head, , [Int], ( ) .

+1

Source: https://habr.com/ru/post/1708544/


All Articles