当前位置: 动力学知识库 > 问答 > 编程问答 >

haskell - Non-exhaustive pattern in my function head'

问题描述:

transpose' :: [[a]] -> [[a]]

transpose' [[]] = []

transpose' [[], _] = []

transpose' rows = (map head' rows) : transpose' (map tail' rows)

where

head' (x:_) = x

tail' (_:xs) = xs

matMult3 :: (Num a) => [[a]] -> [[a]] -> [[a]]

matMult3 a b = [ [ sum $ zipWith (*) ar bc | bc <- (transpose' b) ] | ar <- a ]

Anyone got any ideas as to why this could be throwing up a non-exhaustive? I feel like there is something missing but I'm too new to haskell itself to actually know, I'm self teaching it so that might be why, any advice would be appreciated.

网友答案:

Both head' and tail' don't define what happens if you provide the empty list as a parameter. You need to define the following:

head' [] = ....
tail' [] = ....
网友答案:

I'm not very fluent yet in Haskell, however the following version of transpose' works well for non-ragged matrices:

transpose' :: [[a]] -> [[a]]
transpose' ([x]: xs) = [x: map singleTail' xs] where
    singleTail' [x] = x
transpose' rows = (map head rows) : transpose' (map tail rows) 

E.g.,

>>> transpose' [[1], [2], [3]]
[[1,2,3]]

>>> transpose' [[1,2,3]]
[[1], [2], [3]]

>>> transpose' [[1, 2], [2, 3], [3, 4]]
[[1,2,3],[2,3,4]]

but fails for ragged matrices:

>>> transpose' [[1, 2], [2, 3], [3, 4, 5]]
:3:5-23: Non-exhaustive patterns in function singleTail'
分享给朋友:
您可能感兴趣的文章:
随机阅读: