|
|
|
![]() |
|
Strumenti |
![]() |
#1 |
Member
Iscritto dal: Mar 2008
Messaggi: 47
|
[Haskell] Funzioni IO()
Ho un problema con un programma in Haskell. Devo implementare una funzione che, data una lista di coppie [ ( String, [String] ) ] mi generi una funzione IO (String -> String) che ritorna un elemento scelto a caso dalla lista in ingresso.
In breve: da [("prima", ["A", "B"]), ("seconda", ["C"])] potrebbe generare due funzioni f1 "prima" = "A" f1 "seconda" = "C" e f2 "prima" = "B" f2 "seconda" = "C" Questa è la definizione della funzione: Codice:
stateOfMind :: BotBrain -> IO (Phrase -> Phrase) stateOfMind brain = do r <- randomIO :: IO Float return (rulesApply (zip ps (pick r pps))) where (ps, pps) = unzip brain Questo è quello che risponde l'interprete: Codice:
> :type stateOfMind stateOfMind :: BotBrain -> IO (Phrase -> Phrase) > let mind = stateOfMind brain > :type mind mind :: IO (Phrase -> Phrase) Codice:
> :type phrase phrase :: Phrase > :type phrase2 phrase :: IO Phrase > mind phrase <interactive>:1:0: Couldn't match expected type `IO Phrase -> t' against inferred type `IO (Phrase -> Phrase)' In the expression: mind phrase In the definition of `it': it = mind phrase > mind phrase2 <interactive>:1:0: Couldn't match expected type `Phrase -> t' against inferred type `IO (Phrase -> Phrase)' In the expression: mind phrase2 In the definition of `it': it = mind phrase2 |
![]() |
![]() |
![]() |
#2 |
Senior Member
Iscritto dal: Dec 2005
Città: Istanbul
Messaggi: 1817
|
Tu genere una funzione con tipo "IO (Phrase -> Phrase)", ma in realta' ti serve una funzione Phrase -> IO Phrase
La differenza e' che la prima, quando valutata nel IO Monad, senza argomenti, ti ritorna la funzione, l'altra quando la valuti nell'ambito del Monad, passandogli la frase con argomento, ritorna come risultato l'output voluto Puoi comunque fare lo stesso, sol ocon un passo in piu': prima valuti trovi la funzione e poi la applichi "puramente" ovvero Codice:
let mind = stateOfMind brain function <- mind -- Function ora ha tipo Phrase -> Phrase let result = function phrase -- result ha tipo Phrase Codice:
mind <- stateOfMind brain let result = mind phrase
__________________
One of the conclusions that we reached was that the "object" need not be a primitive notion in a programming language; one can build objects and their behaviour from little more than assignable value cells and good old lambda expressions. —Guy Steele |
![]() |
![]() |
![]() |
#3 | |
Member
Iscritto dal: Mar 2008
Messaggi: 47
|
Quote:
Codice:
let mind = stateOfMind brain function <- mind -- Function ora ha tipo Phrase -> Phrase let result = function phrase -- result ha tipo Phrase Sì, volevo solo sapere come convertire IO (Phrase -> Phrase) in Phrase -> IO Phrase, cioè usare <-. Mi riguarderò il capitolo sui Monad. Grazie mille |
|
![]() |
![]() |
![]() |
Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 08:06.