2015-04-06 83 views
0

我在Haskell中定義函數時遇到問題。我想要做的輸入EnvV類型的變量和Store類型之一,並返回一個State類型變量:Haskell函數定義

type Variable = String 
type Z = Integer 
type T = Bool 
type State = Variable -> Z 
type Location = Z 
type Store = Location -> Z 
type EnvV = Variable -> Location 

search :: EnvV -> Store -> State 
search envV store = envV(store) 
+1

類型的函數'EnvV'需要'Variable'又名'String',當你把它應用到'Store'。請詳細說明你想要做什麼。 – bereal 2015-04-06 09:21:56

+1

無關注:功能應用程序不需要括號(所以你應該寫'envV store'而不是'envV(store)')。 – 2015-04-06 09:25:16

回答

0

嘗試匹配類型:

EnvV這是Variable -> LocationStore這是Location -> Z

你想要的State,其輸出是Variable -> Z

你能看到它們之間的連接?你必須消除它們之間的Location

search :: EnvV -> Store -> State 
search envV store = \x -> store (envV x) 

既然你在輸出要Variable,引進x其表示。然後將其應用於envV,它會給你Location。現在將其應用於store,這將給Z。這會給你一個Variable -> Z這是你期望的類型。

這可以更簡明地寫:

search :: EnvV -> Store -> State 
search envV store = store . envV 
1

你的問題似乎簡化爲:

type State = String -> Integer 
type Store = Integer -> Integer 

search :: State -> Store -> State 

有無限多的方法來實現這一點,但我會猜測你想要的結果只是兩個函數的組成。

search state store = store . state 

或者更簡單地說

search = flip (.) 
0

類型

search :: EnvV -> Store -> State 

意味着

search :: EnvV -> Store -> Variable -> Z 

因此,您可以使用

search envV store var = store (envV var) 

因爲envV varLocation,然後將其應用於store以產生Z

注意下面的代碼是正確的,即使這是一個有點令人費解

search :: EnvV -> Store -> State 
search envV store var = store (envV var) 

它令人費解,因爲它的類型顯示兩個參數,當下面的代碼有三個。同樣地,上面的代碼更常被寫成

search :: EnvV -> Store -> State 
search envV store = \var -> store (envV var) 

這樣即使在定義中,我們可以找到兩個參數和結果值實際上是State類型的每個變量var映射到其值的函數。

上面的代碼可以進一步簡化爲使用函數組合運算符.,正如@ChrisMartin已經顯示的那樣。