I have been playing around with haskell and I found out that if I write the following function in a code file:
f :: Int -> [a] -> a
f idx str = last $ (take . succ) idx str
then this works totally fine. Naturally, I figured the code would look better without the arguments.
f :: Int -> [a] -> a
f = last $ (take . succ)
But this generates an error when I try to load it into gchi
Couldn't match expected type `[a]'
against inferred type `Int -> [a1] -> [a1]'
In the second argument of `($)', namely `(take . succ)'
In the expression: last $ (take . succ)
In the definition of `f': f = last $ (take . succ)
Failed, modules loaded: none.
I'm kind of confused about how this could be happening...
You're misunderstanding the precedence. This:
f idx str = last $ (take . succ) idx str
Is parsed like this:
f idx str = last $ ( (take . succ) idx str )
Not (as you think) like this:
f idx str = ( last $ (take . succ) ) idx str
$ has extremely the lowest precedence of any operator, and function calling has extremely the highest. . has the second highest, so (take . succ) binds to it's arguments (idx str) before it binds to last $.
Furthermore, the function (as it compiles) doesn't do what it looks like you want it to do. It increments idx, then takes that character from the string. If that's what you want, why use succ when (+1) works? You've already restricted the type to integers.
As written, your function is identical to the !! operator - it's just an array index function. Is this what you want? Or do you want to succ the item at the given index? You could accomplish that with the following:
f :: Enum a => Int -> [a] -> a
f idx str = succ $ str !! idx
-- or
f idx str = succ $ (!!) str idx
-- or, only one argument
f idx = succ . (!! idx)
I'm still working on a version with no written arguments. Perhaps it's more important to write working code? ;)
This is what happens when you try to compose last with (take . succ)
:t (.)
(.) :: (b -> c) -> (a -> b) -> a -> c
last :: [t] -> t ~ (b -> c)
-- so b ~ [t] and c ~ t
(take . succ) :: Int -> [t] -> [t]
-- so a ~ int and b ~ [t] -> [t]
Type of b is inferred to be [t] from last but it couldn't match against the type of b in (take . succ) which is [t] -> [t]
f idx str = last $ (take . succ) idx str
-- applying definition of ($)
f idx str = last ((take . succ) idx str)
-- adding parentheses for clarity
f idx str = last (((take . succ) idx) str)
-- using definition of (.)
f idx str = (last . (take . succ) idx) str
-- η-conversion
f idx = last . (take . succ) idx
-- infix to prefix notation
f idx = (.) last ((take . succ) idx)
-- ading parentheses for clarity
f idx = ((.) last) ((take . succ) idx)
-- using definition of (.)
f idx = ((.) last . (take . succ)) idx
-- η-conversion
f = (.) last . (take . succ)
-- remove parentheses: (.) is right-associative
f = (.) last . take . succ
Related
How is it possible to compose n maps in Haskell?
I've tried doing it recursively:
composeMap 0 f = (\x -> x)
composeMap n f = (.) f (composeMap (n-1) f)
And iteratively:
composeMap' n k f g =
if n == k then g
else composeMap' n (k+1) f (f . g)
composeMap n f = composeMap' n 0 f (\x -> x)
But to no avail. Haskell thinks I am constructing an infinite type.
This is obviously false as the function defined is finite for any
n >= 0.
Any suggestions?
Some have posted solutions treating f as having the following type signature:
f :: a -> a
However, I want this to work for f s.t. f is polymorphic in the following way:
f :: a -> a'
f :: a' -> a''
In particular, I want a function that works for the function map, with possible type signatures:
map :: (a -> b) -> [a] -> [b]
map (polymorphic) :: ([a] -> [b]) -> [[a]] -> [[b]]
The function compiles perfectly fine, but Haskell infers the following type signature, which is not what I want:
composeMap'' :: Int -> (b -> b) -> b -> b
I've even tried wrapping map in a monad, but Haskell still thinks I'm constructing an infinite type:
composeMap n f = foldl (>>=) f (replicate n (\x -> return (map x)))
Edit:
I got what I want with the following template Haskell code. Pretty sweet.
This is for declaring the composed map functions:
composeMap :: Int -> Q Dec
composeMap n
| n >= 1 = funD name [cl]
| otherwise = fail "composeMap: argument n may not be <= 0"
where
name = mkName $ "map" ++ show n
composeAll = foldl1 (\fs f -> [| $fs . $f |])
funcs = replicate n [| map |]
composedF = composeAll funcs
cl = clause [] (normalB composedF) []
This is for inlining the composed map. It is more flexible:
composeMap :: Int -> Q Exp
composeMap n = do
f <- newName "f"
maps <- composedF
return $ LamE [(VarP f)] (AppE maps (VarE f))
where
composeAll = foldl1 (\fs f -> [| $fs . $f |])
funcs = replicate n [| map |]
composedF = composeAll funcs
Also, the guys who put the question on hold didn't even understand the question in the first place...
I am afraid I am missing something. Your first implementation compiles and works fine for me (ghc 8.0.2).
Your second implementation failed to compile because you forgot the ' in the else clause. Here is my complete source file:
composeMap1 0 f = (\x -> x)
composeMap1 n f = (.) f (composeMap1 (n-1) f)
composeMap2' n k f g =
if n == k then g
else composeMap2' n (k+1) f (f . g)
composeMap2 n f = composeMap2' n 0 f (\x -> x)
And some tests
λ: :l question.hs
[1 of 1] Compiling Main ( question.hs, interpreted )
Ok, modules loaded: Main.
λ: doubleQuote = composeMap1 2 (\x -> "'" ++ x ++ "'")
λ: doubleQuote "something"
"''something''"
λ: doubleQuote = composeMap2 2 (\x -> "'" ++ x ++ "'")
λ: doubleQuote "something"
"''something''"
λ: plusThree = composeMap1 3 (+1)
λ: plusThree 10
13
λ: plusThree = composeMap2 3 (+1)
λ: plusThree 10
13
I have a task in Haskell (no, it's not my homework, I'm learning for exam).
The task is:
Write point-free function numocc which counts occurrences of element in given lists. For example: numocc 1 [[1, 2], [2, 3, 2, 1, 1], [3]] = [1, 2, 0]
This is my code:
addif :: Eq a => a -> Int -> a -> Int
addif x acc y = if x == y then acc+1 else acc
count :: Eq a => a -> [a] -> Int
count = flip foldl 0 . addif
numocc :: Eq a => a -> [[a]] -> [Int]
numocc = map . count
numocc and count are 'point-free', but they are using function addif which isn't.
I have no idea how can I do the function addif point-free. Is there any way to do if statement point-free? Maybe there is a trick which use no if?
I would use the fact that you can easily convert a Bool to an Int using fromEnum:
addif x acc y = acc + fromEnum (x == y)
Now you can start applying the usual tricks to make it point-free
-- Go prefix and use $
addif x acc y = (+) acc $ fromEnum $ (==) x y
-- Swap $ for . when dropping the last argument
addif x acc = (+) acc . fromEnum . (==) x
And so on. I won't take away all the fun of making it point free, especially when there's tools to do it for you.
Alternatively, you could write a function like
count x = sum . map (fromEnum . (==) x)
Which is almost point free, and there are tricks that get you closer, although they get pretty nasty quickly:
count = fmap fmap fmap sum map . fmap fmap fmap fromEnum (==)
Here I think it actually looks nicer to use fmap instead of (.), although you could replace every fmap with (.) and it would be the exact same code. Essentially, the (fmap fmap fmap) composes a single argument and a two argument function together, if you instead give it the name .: you could write this as
count = (sum .: map) . (fromEnum .: (==))
Broken down:
> :t fmap fmap fmap sum map
Num a => (a -> b) -> [a] -> b
So it takes a function from b to a numeric a, a list of bs, and returns an a, not too bad.
> :t fmap fmap fmap fromEnum (==)
Eq a => a -> a -> Int
And this type can be written as Eq a => a -> (a -> Int), which is an important thing to note. That makes this function's return type match the input to fmap fmap fmap sum map with b ~ Int, so we can compose them to get a function of type Eq a => a -> [a] -> Int.
why not
numocc x
= map (length . filter (== x))
= map ((length .) (filter (== x)) )
= map (((length .) . filter) (== x))
= map (((length .) . filter) ((==) x))
= map (((length .) . filter . (==)) x)
= (map . ((length .) . filter . (==))) x
= (map . (length .) . filter . (==)) x
and then the trivial eta-contraction.
One trick would be to import one of the many if functions, e.g. Data.Bool.bool 1 0 (also found in Data.Bool.Extras).
A more arcane trick would be to use Foreign.Marshal.Utils.fromBool, which does exactly what you need here. Or the same thing, less arcane: fromEnum (thanks #bheklilr).
But I think the simplest trick would be to simply avoid counting yourself, and just apply the standard length function after filtering for the number.
Using the Enum instance for Bool, it is possible to build a pointfree replacement for if that can be used in more general cases:
chk :: Bool -> (a,a) -> a
chk = ([snd,fst]!!) . fromEnum
Using chk we can define a different version of addIf:
addIf' :: Eq a => a -> a -> Int -> Int
addIf' = curry (flip chk ((+1),id) . uncurry (==))
Now we can simply replace chk in addIf':
addIf :: Eq a => a -> a -> Int -> Int
addIf = curry (flip (([snd,fst]!!) . fromEnum) ((+1),id) . uncurry (==))
I think you’re looking for Data.Bool’s bool, which exists since 4.7.0.0 (2014–04–08).
incif :: (Eq a, Enum counter) => a -> a -> counter -> counter
incif = ((bool id succ) .) . (==)
The additional . allows == to take two parameters, before passing the expression to bool.
Since the order of parameters is different, you need to use incif like this:
(flip . incif)
(Integrating that into incif is left as an exercise to the reader. [Translation: It’s not trivial, and I don’t yet know how. ;])
Remember that in Haskell list comprehensions, if conditionals can be used in the result clause or at the end. But, most importantly, guards without if can be used to filter results. I am using pairs from zip. The second of the pair is the list number. It stays constant while the elements of the list are being compared to the constant (k).
Your result [1,2,0] does not include list numbers 1, 2 or 3 because it is obvious from the positions of the sums in the result list. The result here does not add the occurrences in each list but list them for each list.
nocc k ls = [ z | (y,z) <- zip ls [1..length ls], x <- y, k == x]
nocc 1 [[1, 2], [2, 3, 2, 1, 1], [3]]
[1,2,2] -- read as [1,2,0] or 1 in list 1, 2 in list 2 and 0 in list 3
I have two functions:
firstfunc :: (RandomGen g) => g -> Int -> Float -> [[Int]]
firstfunc rnd n p = makGrid $ map (\t -> if t <= p then 1 else 0) $ take (n*n) (randoms rnd)
where makGrid rnd = unfoldr nextRow (rnd, n)
nextRow (_, 0) = Nothing
nextRow (es, i) = let (rnd, rest) = splitAt n es in Just (rnd, (rest, i-1))
sndfunc firstfunc = head $ do
lst <- firstfunc
return $ map (\x -> if (x == 0) then 2 else x) lst
let newFunc = ((firstfunc .) .) . sndfunc
main = do
gen <- getStdGen
let g = (firstfunc gen 5 0.3)
print g
let h = sndfunc g
print h
print $ newFunc gen 5 0.3
The firstfunc takes two values like 5 and 0.3 and returns a list of lists like: [[0,0,0,1,0],[1,0,0,1,0],[0,0,1,1,0],[0,0,0,0,0],[1,0,0,0,1]]
The sndfunc takes the head of the above list of lists, which is [1,0,0,1,0] from the above example, and replaces the zeroes with 2s like this: [1,2,2,1,2].
Is there a way to combine the two functions such that the firstfunc only returns something like: [[1,2,2,1,2],[0,0,1,1,0],[0,0,0,0,0],[1,0,0,0,1]]?
ERROR:
getting parse error parse error (possibly incorrect indentation or mismatched brackets) on this line: let newFunc = ((firstfunc .) .) . sndfunc
2nd EDIT:
prac.hs:15:32:
Couldn't match type ‘[b]’ with ‘a -> a1 -> b0’
Expected type: [[b]] -> a -> a1 -> b0
Actual type: [[b]] -> [b]
Relevant bindings include
newFunc :: [[b]] -> a -> a1 -> Int -> Float -> [[Int]]
(bound at prac.hs:15:1)
In the second argument of ‘(.)’, namely ‘sndfunc’
In the expression: (((firstfunc .) .) . sndfunc)
Failed, modules loaded: none.
You can either use
print $ sndfunc $ firstfunc gen 5 0.3
or you can define a new function
let newFunc = ((sndfunc .) .) . firstfunc
and use that.
print $ newFunc gen 5 0.3
(the extra (.) operators are needed because firstfunc takes three inputs).
I've tried to transform the following list comprehension:
f xs = [ x+8 | (x,_) <- xs ]
using higher-order functions.
My first solution was:
f' xs = map (\(x,_) -> x+8) xs
After I tried various other approaches, I found out that the following also works:
f' xs = map((+8).fst) xs
Both versions of f' give the same (correct) output, but I don't understand why (+8).fst is equal to \(x,_) -> x+8 when using map on a list of tuples.
The definition of fst is
fst :: (a, b) -> a
fst (a, _) = a
and the definition of (.) is
(.) :: (b -> c) -> (a -> b) -> a -> c
(f . g) = \x -> f (g x)
If we use these definitions to expand your function, we get
f' xs = map ((+8) . fst) xs
f' xs = map (\x -> (+8) (fst x)) xs -- definition of (.)
f' xs = map (\x -> (+8) ((\(a, _) -> a) x)) -- definition of fst
f' xs = map (\(a, _) -> (+8) a) -- we can move the pattern matching
f' xs = map (\(a, _) -> a + 8) -- expand section
Both versions of f' give the same (correct) output, but I don't understand why (+8).fst is equal to (x,_) -> x+8 when using map on a list of tuples.
The type of fst is:
fst :: (a, b) -> a
and what it does is it takes the first element of a pair (a tuple of two elements).
The type of (+8) is:
(+8) :: Num a => a -> a
and what it does is it takes as input a Num, applies + 8 to it and returns the result.
Now, the type of (+8) . fst is:
((+8).fst) :: Num c => (c, b) -> c
which is the composition of fst and (+8). Specifically it's the function that takes as input a pair, extracts the first element and adds 8 to it.
This can be easily seen by seen an example:
((+8).fst) (3, 'a')
-- 11
The same thing happens with \ (x, _) -> x + 8. You take a pair as input (in the lambda), pattern match the first argument to x, increment it by 8 and return it:
(\ (x, _) -> x + 8) (3, 'a')
-- 11
I have been learning some Haskell and I came up with a solution to one of my exercise which I was trying to figure out .
Changes a Char to another specified Char in a specified position in a String
changeStr :: Int -> Char -> String -> String
changeStr x char zs = (take (x-1) zs) ++ [(changeChar (head (take x zs)) char)] ++ (drop x zs)
Changes a Char to another Char
changeChar :: Char -> Char -> Char
changeChar x y = y
I just wanted to ask is there any other way in which I could do this in a more simpler way using different methods ?
The thing that screams for generalization is changeChar. It's actually very close to a very common Haskell Prelude function called const. To get changeChar we just need to flip const.
const :: a -> b -> a
const a b = a
changeChar :: Char -> Char -> Char
changeChar = flip const
-- = flip (\a _ -> a)
-- = \_ a -> a
-- _ a = a
Beyond that, your code is fairly reasonable, but can be cleaned up by using a function splitAt
splitAt :: Int -> [a] -> ([a], [a])
splitAt n xs = (take n xs, drop n xs)
changeChar x char xs =
let (before, _it:after) = splitAt (x - 1)
in before ++ (char:after)
which also highlights a slight problem with this definition in that if your index is too large it will throw a pattern matching failure. We could fix that by making the function return an unmodified string if we "fall off the end"
changeChar x char xs =
let (before, after) = splitAt (x - 1)
in case after of
[] -> []
(_:rest) -> char:rest
There's a general pattern here as well of applying a modifying function at a particular place in a list. Here's how we can extract that.
changeAt :: Int -> (a -> a) -> [a] -> [a]
changeAt n f xs =
let (before, after) = splitAt (n-1)
in case after of
[] -> []
(x:rest) -> (f x):rest
We can use this to iterate the notion
-- | Replaces an element in a list of lists treated as a matrix.
changeMatrix :: (Int, Int) -> a -> [[a]] -> [[a]]
changeMatrix (i, j) x = changeAt i (changeAt j (const x))
What you have is pretty much what you need, except the function changeChar is just flip const, and you could rewrite yours as
changeStr x char zs = take (x-1) zs ++ [char] ++ drop x zs
If you wanted to be complicated, you could use splitAt from Data.List and the fact that fmap f (a, b) = (a, f b)
changeStr idx c str = uncurry (++) $ fmap ((c:) . tail) $ splitAt (idx - 1) str
And if you wanted to be really complicated, you could ask the pointfree bot how to write it without explicit function arguments
changeStr = ((uncurry (++) .) .) . flip ((.) . fmap . (. tail) . (:)) . splitAt . subtract 1