写函数得到第k个元素

时间:2017-02-01 15:10:38

标签: haskell

我写了以下代码:

getElement :: [a] -> Integer -> a
getElement (x:xs) 1 = x
getElement (x:xs) n = getElement $ xs (n-1)

main :: IO()
main = print $ getElement $ [1, 2, 3, 4, 5] 2

但它一直给我以下错误:

/home/jaisingh/cs/Course/POPL/Assignment/Assignment 1/problem3.hs:3:36:
    Couldn't match expected type ‘Integer -> [a0]’
                with actual type ‘[a]’
    Relevant bindings include
      xs :: [a]
        (bound at /home/jaisingh/cs/Course/POPL/Assignment/Assignment 1/problem3.hs:3:15)
      x :: a
        (bound at /home/jaisingh/cs/Course/POPL/Assignment/Assignment 1/problem3.hs:3:13)
      getElement :: [a] -> Integer -> a
        (bound at /home/jaisingh/cs/Course/POPL/Assignment/Assignment 1/problem3.hs:2:1)
    The function ‘xs’ is applied to one argument,
    but its type ‘[a]’ has none
    In the second argument of ‘($)’, namely ‘xs (n - 1)’
    In the expression: getElement $ xs (n - 1)

/home/jaisingh/cs/Course/POPL/Assignment/Assignment 1/problem3.hs:6:29:
    Couldn't match expected type ‘Integer -> [a1]’
                with actual type ‘[Integer]’
    The function ‘[1, 2, 3, 4, ....]’ is applied to one argument,
    but its type ‘[Integer]’ has none
    In the second argument of ‘($)’, namely ‘[1, 2, 3, 4, 5] 2’
    In the second argument of ‘($)’, namely
      ‘getElement $ [1, 2, 3, 4, 5] 2’

我认为使用 a 类型变量时函数签名存在一些问题。救救我!

0 个答案:

没有答案