altern
altern

Reputation: 5949

Extracting list of functions into a standalone function in Haskell

I have a pipe of functions fun1 $ fun2 $ fun3 applied to a variable var as fun1 $ fun2 $ fun3 var. How could I extract this pipe fun1 $ fun2 $ fun3 into standalone function fun = (fun1 $ fun2 $ fun3) that can be appllied to a var as fun var?

For example, I have a following pipe of functions: BS.unpack $ JSON.encode var. I want to extract BS.unpack $ JSON.encode from the statement BS.unpack $ JSON.encode var into let fun = BS.unpack . JSON.encode, but I get an error:

No instance for (JSON.ToJSON a0)
  arising from a use of `JSON.encode'
The type variable `a0' is ambiguous

What is wrong with my function extraction?

Upvotes: 1

Views: 72

Answers (1)

Cameron Martin
Cameron Martin

Reputation: 6010

What you're looking for is the function composition operator, .. This works as follows:

(f . g) x = f (g x) = f $ g x

Therefore, fun = fun1 . fun2 . fun3 is what you're looking for.

Upvotes: 6

Related Questions