簡體   English   中英

函數的類型類實例

[英]Typeclass instance for function

我正在研究CIS 194的作業問題。
我被困在家庭作業5 ,問題6。

類型類Expr用於表示包含變量的任何表達式的表達式和類型類HasVars
該問題要求為M.Map String Integer -> Maybe Integer實現Expr實例M.Map String Integer -> Maybe Integer ,其中MData.Map

class Expr a where 
  add :: a -> a -> a
  mul :: a -> a -> a
  lit :: Integer -> a

這是Expr for Integer的代碼。

instance Expr Integer where
  add m n = m + n
  mul m n = m * n
  lit m = m 

並且對於函數的HasVars實例,

instance HasVars (M.Map String Integer -> Maybe Integer) where
   var s  = M.lookup s 

我很困惑如何為函數類型創建Expr實例。 如何進行模式匹配或從函數中提取值? 類型是a-> a -> a ,所以我沒有Map來提取值,而ShowVars var用於將String轉換為所述函數。

我沒有提出問題的其他部分的解決方案,因為它可能包含劇透。

好吧,首先寫出簽名,以便清楚應該是什么東西。 為了使它更具可讀性,

type MS2I = M.Map String Integer
type Integer' = Maybe Integer

然后

add :: (MS2I -> Integer') -> (MS2I -> Integer') -> (MS2I -> Integer')

所以你可以先開始吧

add m n = o
 where m, n, o :: MS2I -> Integer'

所以o是一個采用地圖的函數......你可以定義:

add m n = o
 where o ms2i = ...

那時你就有了一張地圖。 您可以將其提供給參數:

add m n = o
 where o ms2i = let i1 = m ms2i
                    i2 = n ms2i
                    i1, i2 :: Integer'
                in ...?   

其余應該是顯而易見的,你只需要將兩個Maybe Integer組合成一個新的。 (最好使用Applicative 。)

有趣和參考,這是一個超級濃縮版本:

import Control.Arrow
instance Expr (Kleisli Maybe MS2I Integer) where
  add m n = arr (uncurry(+)) . (m&&&n)

暫無
暫無

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

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