[英]Composition with lambda expressions haskell
我嘗試了一個使用 lambda 表達式組合的虛擬示例。 下面的代碼可以編譯,但是當我嘗試(fg) 3 2
時它沒有運行
f x = x^2
g x = 5*x
f.g = \x -> f(g x)
它給出了這樣的錯誤:
Ambiguous occurrence `.'
It could refer to
either `Prelude..',
imported from `Prelude' at list3.hs:1:1
(and originally defined in `GHC.Base')
or `Main..', defined at list3.hs:42:3.
有人可以告訴我問題出在哪里嗎?
您定義了一個合成運算符,它與從 Prelude 導入的運算符並存。 定義沒有錯; 當您嘗試使用它時會出現問題,因為編譯器無法判斷是否像
main = print $ f . g $ 10
應該使用.
從序曲或.
從你的Main
模塊。
一種解決方案是簡單地明確說明您想要兩者中的哪一個。
f . g = \x -> f (g x)
main = print $ f Main.. g $ 10
或者首先不導入 Prelude 版本。
{-# LANGUAGE NoImplicitPrelude #-}
import Prelude hiding ((.))
-- Now this is the *only* definition.
f . g = \x -> f (g x)
main = print $ f . g $ 10
正如 chepner 在出色的回答中所解釋的那樣,你的 '.' 點運算符與常規“.”沖突從 Haskell Prelude 隱式導入的運算符。 這就是錯誤消息的意思。
幸運的是,Haskell 編譯器支持Unicode字符集,它恰好提供了數學書上看到的正確的 function 組合字符,即“∘”,十進制為 position 8728。
而這個“∘”運算符(目前)還沒有被 Prelude 定義。
因此,以下代碼可以正常工作:
main :: IO ()
main = do
let
-- our own function composition operator:
fna ∘ fnb = \x -> fna (fnb x) -- Unicode character #8728 (decimal)
f x = x * x
g x = 5 * x
h = f ∘ g -- composed function
res = h 7
putStrLn $ "res = " ++ (show res)
正如您所期望的那樣,它會打印出 1225 的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.