Here is the problem, i need to write the well known twice function
(twice= \x-> \x-> x)
but this time using (.)
composition function like (.) fg
.
I don't know how to solve it, cause I thought at the beginning to do like:
(.) f g = (\x -> f (g x))
with (g = f)
so it would be like this
(.) f f = (\x -> f (f x))
but I have a
"Conflicting definitions for `f'"
running on GHCI
So, any suggestions ?
I don't know how you got anything other than a parse input from this:
(.) f f = (\x -> f (f x))
but the definition you gave: twice = \\x -> \\x -> x
has nothing to do with using something "twice" - indeed if you plug in some values:
twice a b
= (\x -> \x -> x) a b
= (\x -> (\x -> x)) a b -- (rename the inner x)
= (\x -> (\y -> y)) a b
= ((\x -> (\y -> y)) a) b
= (\y -> y) b
= b
and indeed GHCi will tell you the same:
> let twice = \x -> \x -> x
> :t twice
twice :: t -> t1 -> t1
> twice "a" "b"
"b"
Now I guess you want something like this:
let twice f x = f (f x)
for example:
> let twice f x = f (f x)
> twice (+1) 5
7
as you can see twice (+1)
adds 2 (or twice one).
Now how can you do this using (.)
? - Well your intuition was wright:
> let twice f = f . f
> twice (+1) 5
7
As you asked for a module - this compiles (and loads into GHCi) fine on my system(s):
module Twice where
twice :: (a->a) -> a -> a
twice f = f . f
this only works if you include (.)
from the prelude (or GHC.Base) - I suspect that you got some kind of excercise that hid the prelude - in this case you have to define (.)
for yourself first (most likely another excercise)
if you need to implement it yourself:
(.) :: (b -> c) -> (a -> b) -> a -> c
(.) g f x = g (f x)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.