2016-08-11 12 views
8

Nehmen wir an, ich möchte Text.pack mit Text.strip komponieren.Warum benötigt die Funktionszusammensetzung Klammern?

:t (.) produziert: (b -> c) -> (a -> b) -> a -> c

:t (Text.pack) produziert: String -> Text

:t (Text.strip) produziert: Text -> Text

So strip für (b -> c) Substitution gibt: b = Text c = Text

pack für (a -> b) Substituieren gibt: a = String b = Text

Lets überprüfen: :t strip . pack produziert: strip . pack :: String -> Text

ok, große versuchen lässt es:

strip.pack " example "

Produziert:

Couldn't match expected type ‘a -> Text’ with actual type ‘Text’ 
Relevant bindings include 
    it :: a -> Text (bound at <interactive>:31:1) 
Possible cause: ‘pack’ is applied to too many arguments 
In the second argument of ‘(.)’, namely ‘pack " example  "’ 
In the expression: strip . pack " example  " 

(strip . pack) " example " funktioniert wie erwartet .... warum?

Antwort

11

Funktion Anwendung hat eine höhere Priorität als Zusammensetzung.

strip.pack " example " entspricht strip.(pack " example "). Dies ist ein Grund, warum die Menschen $ verwenden, um „unterdrücken“ Anwendung erst nach alle Funktionen zusammengesetzt wurden:

strip . pack $ " example  " 
+8

Noch stärker, Funktion Anwendung hat eine höhere Priorität als * alles andere *. – amalloy

+9

@amalloy ... außer Rekordaktualisierung. = P –

+0

Diese Priorität erlaubt z.B. 'Filter sogar. Karte (+5) '. Partiell angelegte Funktionen zu komponieren ist eher idiomatisch. Beachten Sie auch, dass die Reihenfolge der Argumente für "map, filter, ..." ausgewählt wurde, um dies bequem zu machen. – chi

1

Funktion Anwendung hat eine höhere Priorität über die Funktion Zusammensetzung Operator.

Verwandte Themen