簡體   English   中英

為什么在Haskell中無法進行最后的初始化?

[英]Why does feeding init to last not work in Haskell?

因此,我正在寫一行以獲取列表的倒數第二個元素。 最初我的代碼是

mySLast x = last.take ((length x) - 1) x

直到last功能。 實現了我的take業務已經包含在Haskell作為init ,所以我改寫為

mySLast = last.init 

這仍然行不通。 我感到困惑的是因為init::[a]->[a]last::[a]->a所以它們在Hask類別中絕對應該是可組合的詞素

我試圖問Haskell,它認為類型是什么,它說

ghci> :t last.init
last.init :: [c] -> c
ghci> last.init [3,2,4,1]

<interactive>:45:6:
    Couldn't match expected type ‘a -> [c]’
                with actual type ‘[Integer]’
     Relevant bindings include
       it :: a -> c (bound at <interactive>:45:1)
    Possible cause: ‘init’ is applied to too many arguments
     In the second argument of ‘(.)’, namely ‘init [3, 2, 4, 1]’
     In the expression: last . init [3, 2, 4, 1]

即使

ghci> init [3,2,4,1]
[3,2,4]
ghci> last [3,2,4]
4

因此,我一定會誤解有關在Haskell中編寫函數的知識。 任何見解將不勝感激!

函數應用程序比(.)綁定更緊密

last.init [3,2,4,1]

被解析為

last . (init [3,2,4,1])

您可以使用

(last . init) [3,2,4,1]

要么

last . init $ [3,2,4,1]

您忘記了init和列表之間的$ ,例如

last . init $ [3,2,4,1]
            ↑ See here 

此問題的另一種解決方案是,僅評估列表的(書脊)直至所需元素,而不使用長度(在返回所需元素之前將評估整個書脊):

takeTail n xs = go (drop n xs) xs
  where
    go (_:ys) (_:xs) = go ys xs 
    go []     xs     = xs  -- Stop and return xs when ys runs out

> head . takeTail 2 $ [1,2,3,4]
3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM