Can't understand result when calling applyTwice multiple times - haskell

There are many questions based on applyTwice, but none that relate to my problem. I understand that the applyTwice function defined like this:
applyTwice :: (a -> a) -> a -> a
applyTwice f a = f (f a)
applies a function twice. So if I have an increment function:
increment x = x + 1
and do
applyTwice increment 0
I get 2. But I don't understand these results:
applyTwice applyTwice applyTwice increment 0 -- gives 16
applyTwice applyTwice applyTwice applyTwice increment 0 -- gives 65536
applyTwice applyTwice applyTwice applyTwice applyTwice increment 0 -- stack overflow
I also know that
twice = applyTwice applyTwice increment
applyTwice twice 0 -- gives 8
I simply cannot wrap my head around these results, would love it if someone could explain. I apologize if this is something basic, as I'm just learning Haskell.

Let's use the informal notation
iter n f = f . f . f . .... -- n times
Your applyTwice is then simply iter 2.
From the definition, we immediately get:
(iter n . iter m) f
= iter n (iter m f)
= (f.f. ...) . ... . (f.f. ...) -- n times (m times f)
= iter (n*m) f
hence, eta contracting,
iter n . iter m = iter (n*m) -- [law 1]
We also have
iter n (iter m)
= -- definition
iter m . iter m . .... . iter m -- n times
= -- law 1
iter (m*m* ... *m) -- n times
= -- power
iter (m^n) -- [law 2]
We then have, writing t for applyTwice:
t = iter 2
t t
= -- previous equation
iter 2 (iter 2)
= -- law 2
iter (2^2)
t t t
= -- left associativity of application
(t t) t
= -- previous equation
iter (2^2) (iter 2)
= -- law 2
iter (2^(2^2))
t t t t
= -- left associativity of application
(t t t) t
= -- previous equation
iter (2^(2^2)) (iter 2)
= -- law 2
iter (2^(2^(2^2)))
and so on.

There is a lot of complexity hiding behind the scenes in the form of invisible type arguments. What happens if we write these arguments out with -XTypeApplications. I have shortened some of the names.
The following twice is instantiated at twice #Int whose type is second-order.
one :: Int
one = twice (+ 1) 0
^^^^^
|
twice #Int
:: (Int -> Int)
-> (Int -> Int)
When you apply twice (order-3) to twice (order-2) the type signature becomes more complicated.
two :: Int
two = twice twice (+ 1) 0
^^^^^ ^^^^^
| |
| twice #Int
| :: (Int -> Int)
| -> (Int -> Int)
|
twice #(Int->Int)
:: ((Int->Int) -> (Int->Int))
-> ((Int->Int) -> (Int->Int))
And so forth, when you have twice twice twice they are order-4, order-3 and order-2 respectively:
three :: Int
three = twice twice twice (+ 1) 0
^^^^^ ^^^^^ ^^^^^
| | |
| | twice #Int
| | :: (Int -> Int)
| | -> (Int -> Int)
| |
| twice #(Int->Int)
| :: ((Int->Int) -> (Int->Int))
| -> ((Int->Int) -> (Int->Int))
|
twice #((Int->Int)->(Int->Int))
:: (((Int->Int)->(Int->Int)) -> ((Int->Int)->(Int->Int)))
-> (((Int->Int)->(Int->Int)) -> ((Int->Int)->(Int->Int)))
the last example you gave becomes this monstrosity with order-6, order-5, order-4, order-3, order-2 respectively...
{-# Language TypeApplications #-}
five :: Int
five = twice #((((Int->Int)->(Int->Int))->((Int->Int)->(Int->Int)))->(((Int->Int)->(Int->Int))->((Int->Int)->(Int->Int))))
(twice #(((Int->Int)->(Int->Int))->((Int->Int)->(Int->Int))))
(twice #((Int->Int)->(Int->Int)))
(twice #(Int->Int))
(twice #Int)
(+ 1) 0
So this is the type of the first twice!!
twice #((((Int->Int)->(Int->Int))->((Int->Int)->(Int->Int)))->(((Int->Int)->(Int->Int))->((Int->Int)->(Int->Int))))
:: (((((Int -> Int) -> Int -> Int) -> (Int -> Int) -> Int -> Int)
-> ((Int -> Int) -> Int -> Int) -> (Int -> Int) -> Int -> Int)
-> (((Int -> Int) -> Int -> Int) -> (Int -> Int) -> Int -> Int)
-> ((Int -> Int) -> Int -> Int)
-> (Int -> Int)
-> Int
-> Int)
-> ((((Int -> Int) -> Int -> Int) -> (Int -> Int) -> Int -> Int)
-> ((Int -> Int) -> Int -> Int) -> (Int -> Int) -> Int -> Int)
-> (((Int -> Int) -> Int -> Int) -> (Int -> Int) -> Int -> Int)
-> ((Int -> Int) -> Int -> Int)
-> (Int -> Int)
-> Int
-> Int

Related

How to pass not a function that returns a boolean in another function?

I want to negate a function in the if clause of another function like bellow:
isBig :: Integer -> Bool
isBig n = n > 9999
function :: Integer -> Integer
function n =
if not isBig n then ... else ...
It complies when it's just 'if isBig n then else' but I'm not sure why it doesn't work for 'not isBig' as I get this error:
*Couldn't match expected type Bool' with actual type Integer -> Bool'
Many thanks in advance.
You want not (isBig n). not isBig n tries to pass two arguments to not, both isBig and n. isBig is an Integer -> Bool but a Bool is expected, hence the error.
In general, function application in Haskell is left-associative, meaning that an expression like this:
f 2 3 5
Is parsed like this:
(((f 2) 3) 5)
Likewise, the arrows in function types are right-associative, so for example if we had this definition for f:
f :: Int -> Int -> Int -> Int
f x y z = x * y + z
That type signature is the same as:
f :: Int -> (Int -> (Int -> Int))
So it looks like this as you apply more arguments:
f :: Int -> (Int -> (Int -> Int))
(f 2) :: (Int -> (Int -> Int))
((f 2) 3) :: (Int -> Int)
(((f 2) 3) 5 :: Int
==
f :: Int -> Int -> Int -> Int
f 2 :: Int -> Int -> Int
f 2 3 :: Int -> Int
f 2 3 5 :: Int
When you’re applying a chain of functions to an argument, you end up with parentheses associating to the right:
f (g (h x))
In this case it’s common to use the $ operator, which is right-associative and has low precedence, just to reduce the nesting of brackets:
f $ g $ h x
And you can do so in your case: not $ isBig n
You can also use composition to factor out the chain of functions and apply it to different arguments elsewhere:
fgh = f . g . h
fgh x
==
(f . g . h) x
==
f (g (h x))
isNotBig = not . isBig
isNotBig n
==
(not . isBig) n
==
not (isBig n)

How to know in Haskell in what row and column of a table ([[a]]) you are

I want to make a sudoku solver in Haskell (as an exercise). My idea is:
I have t :: [[Int]] representing a 9x9 grid so that it contains 0 in an empty field and 1-9 in a solved field.
A function solve :: [[Int]] -> [[Int]] returns the solved sudoku.
Here is a rough sketch of it (i'd like to point out i'm a beginner, i know it is not the most optimal code):
solve :: [[Int]] -> [[Int]]
solve t
| null (filter (elem 0) t) = t
| t /= beSmart t = solve (beSmart t)
| otherwise = guess t
The function beSmart :: [[Int]] -> [[Int]] tries to solve it by applying some solving algorithms, but if methodical approach fails (beSmart returns the unchanged sudoku table in that case) it should try to guess some numbers (and i'll think of that function later). In order to fill in an empty field, i have to find it first. And here's the problem:
beSmart :: [[Int]] -> [[Int]]
beSmart t = map f t
where f row
| elem 0 row = map unsolvedRow row
| otherwise = row
where unsolvedRow a
| a == 0 = tryToDo t r c --?!?!?!?! skip
| otherwise = a
The function tryToDo :: [[Int]]] -> Int -> Int - > Int needs the row and column of the field i'm trying to change, but i have no idea how to get that information. How do i get from map what element of the list i am in at the moment? Or is there a better way to move around in the table? I come from iterative and procedural programing and i understand that perhaps my approach to the problem is wrong when it comes to functional programing.
I know this is not really an answer to your question, but I would argue, that usually you would want a different representation (one that keeps a more detailed view of what you know about the sudoku puzzle, in your attempted solution you can only distinguish a solved cell from a cell that is free to assume any value). Sudoku is a classical instance of CSP. Where modern approaches offer many fairly general smart propagation rules, such as unit propagation (blocking a digit in neighboring cells once used somewhere), but also many other, see AC-3 for further details. Other related topics include SAT/SMT and you might find the algorithm DPLL also interesting. In the heart of most solvers there usually is some kind of a search engine to deal with non-determinism (not every instance must have a single solution that is directly derivable from the initial configuration of the instance by application of inference rules). There are also techniques such as CDCL to direct the search.
To address the question in the title, to know where you are, its probably best if you abstract the traversal of your table so that each step has access to the coordinates, you can for example zip a list of rows with [0..] (zip [0..] rows) to number the rows, when you then map a function over the zipped lists, you will have access to pairs (index, row), the same applies to columns. Just a sketch of the idea:
mapTable :: (Int -> Int -> a -> b) -> [[a]] -> [[b]]
mapTable f rows = map (\(r, rs) -> mapRow (f r) rs) $ zip [0..] rows
mapRow :: (Int -> a -> b) -> [a] -> [b]
mapRow f cols = map (uncurry f) $ zip [0..] cols
or use fold to turn your table into something else (for example to search for a unit cell):
foldrTable :: (Int -> Int -> a -> b -> b) -> b -> [[a]] -> b
foldrTable f z rows = foldr (\(r, rs) b -> foldrRow (f r) b rs) z $ zip [0..] rows
foldrRow :: (Int -> a -> b -> b) -> b -> [a] -> b
foldrRow f z cols = foldr (uncurry f) z $ zip [0..] cols
to find which cell is unital:
foldrTable
(\x y v acc -> if length v == 1 then Just (x, y) else acc)
Nothing
[[[1..9],[1..9],[1..9]],[[1..9],[1..9],[1..9]],[[1..9],[1],[1..9]]]
by using Monoid you can refactor it:
import Data.Monoid
foldrTable' :: Monoid b => (Int -> Int -> a -> b) -> [[a]] -> b
foldrTable' f rows = foldrTable (\r c a b -> b <> f r c a) mempty rows
unit :: Int -> Int -> [a] -> Maybe (Int, Int)
unit x y c | length c == 1 = Just (x, y)
| otherwise = Nothing
firstUnit :: [[[a]]] -> Maybe (Int, Int)
firstUnit = getFirst . foldrTable' (\r c v -> First $ unit r c v)
so now you would do
firstUnit [[[1..9],[1..9],[1..9]],[[1,2],[3,4],[5]]]
to obtain
Just (1, 2)
correctly determining that the first unit cell is at position 1,2 in the table.
[[Int]] is a good type for a sodoku. But map does not give any info regarding the place it is in. This is one of the ideas behind map.
You could zip together the index with the value. But a better idea would be to pass the whole [[Int]] and the indexes to to the function. So its type would become:
f :: [[Int]] -> Int -> Int -> [[Int]]
inside the function you can now access the current element by
t !! x !! y
Already did this a while ago as a learning example. It is definitely not the nicest solution, but it worked for me.
import Data.List
import Data.Maybe
import Data.Char
sodoku="\
\-9-----1-\
\8-4-2-3-7\
\-6-9-7-2-\
\--5-3-1--\
\-7-5-1-3-\
\--3-9-8--\
\-2-8-5-6-\
\1-7-6-4-9\
\-3-----8-"
sodoku2="\
\----13---\
\7-5------\
\1----547-\
\--418----\
\951-67843\
\-2---4--1\
\-6235-9-7\
\--7-98--4\
\89----1-5"
data Position = Position (Int, Int) deriving (Show)
data Sodoku = Sodoku [Int]
insertAtN :: Int -> a -> [a] -> [a]
insertAtN n y xs = intercalate [y] . groups n $ xs
where
groups n xs = takeWhile (not.null) . unfoldr (Just . splitAt n) $ xs
instance Show Sodoku where
show (Sodoku s) = (insertAtN 9 '\n' $ map intToDigit s) ++ "\n"
convertDigit :: Char -> Int
convertDigit x = case x of
'-' -> 0
x -> if digit>=1 && digit<=9 then
digit
else
0
where digit=digitToInt x
convertSodoku :: String -> Sodoku
convertSodoku x = Sodoku $ map convertDigit x
adjacentFields :: Position -> [Position]
adjacentFields (Position (x,y)) =
[Position (i,y) | i<-[0..8]] ++
[Position (x,j) | j<-[0..8]] ++
[Position (u+i,v+j) | i<-[0..2], j<-[0..2]]
where
u=3*(x `div` 3)
v=3*(y `div` 3)
positionToField :: Position -> Int
positionToField (Position (x,y)) = x+y*9
fieldToPosition :: Int -> Position
fieldToPosition x = Position (x `mod` 9, x `div` 9)
getDigit :: Sodoku -> Position -> Int
getDigit (Sodoku x) pos = x !! (positionToField pos )
getAdjacentDigits :: Sodoku -> Position -> [Int]
getAdjacentDigits s p = nub digitList
where
digitList=filter (\x->x/=0) $ map (getDigit s) (adjacentFields p)
getFreePositions :: Sodoku -> [Position]
getFreePositions (Sodoku x) = map fieldToPosition $ elemIndices 0 x
isSolved :: Sodoku -> Bool
isSolved s = (length $ getFreePositions s)==0
isDeadEnd :: Sodoku -> Bool
isDeadEnd s = any (\x->x==0) $ map length $ map (getValidDigits s)$ getFreePositions s
setDigit :: Sodoku -> Position -> Int -> Sodoku
setDigit (Sodoku x) pos digit = Sodoku $ h ++ [digit] ++ t
where
field=positionToField pos
h=fst $ splitAt field x
t=tail$ snd $ splitAt field x
getValidDigits :: Sodoku -> Position -> [Int]
getValidDigits s p = [1..9] \\ (getAdjacentDigits s p)
-- Select numbers with few possible choices first to increase execution time
sortImpl :: (Position, [Int]) -> (Position, [Int]) -> Ordering
sortImpl (_, i1) (_, i2)
| length(i1)<length(i2) = LT
| length(i1)>length(i2) = GT
| length(i1)==length(i2) = EQ
selectMoves :: Sodoku -> Maybe (Position, [Int])
selectMoves s
| length(posDigitList)>0 = Just (head posDigitList)
| otherwise = Nothing
where
posDigitList=sortBy sortImpl $ zip freePos validDigits
validDigits=map (getValidDigits s) freePos
freePos=getFreePositions s
createMoves :: Sodoku -> [Sodoku]
createMoves s=
case selectMoves s of
Nothing -> []
(Just (pos, digits)) -> [setDigit s pos d|d<-digits]
solveStep :: Sodoku -> [Sodoku]
solveStep s
| (isSolved s) = [s]
| (isDeadEnd s )==True = []
| otherwise = createMoves s
solve :: Sodoku -> [Sodoku]
solve s
| (isSolved s) = [s]
| (isDeadEnd s)==True = []
| otherwise=concat $ map solve (solveStep s)
s=convertSodoku sodoku2
readSodoku :: String -> Sodoku
readSodoku x = Sodoku []

Occurs check: cannot construct the infinte type

I'm trying to construct a list of all prime numbers using the sieve method:
primes remNum =
let i = head remNum
in i : primes (filter (\(x) -> x mod i /= 0) (tail remNum))
The error that I'm getting is:
* Occurs check: cannot construct the infinite type:
t ~ (a -> a -> a) -> t -> a1
Expected type: [t]
Actual type: [(a -> a -> a) -> t -> a1]
* In the first argument of `head', namely `remNum'
In the expression: head remNum
In an equation for `i': i = head remNum
* Relevant bindings include
i :: t (bound at lib.hs:30:7)
remNum :: [(a -> a -> a) -> t -> a1] (bound at lib.hs:29:8)
primes :: [(a -> a -> a) -> t -> a1] -> [t] (bound at lib.hs:29:1)
I don't understand why remNum is bound to [(a-> a -> a) -> t -> a1] while i is bound to t, since surely head :: [a] -> a would imply remNum::[t]?
So the idea with this is that it is supplied a lazy list of all numbers and then essentially maintains a list of removed values.
It would be called:
numsFrom n = n : numsFrom (n + 1)
primes numsFrom 2
x mod i
is not what you intended. You want to use
x `mod` i
The problem with the first is that since both i and x are from the list, they must have the same type. Let's call that type X. What is X? Well, since we use x mod, it should start with mod's type:
type X = (Integer -> Integer -> Integer) -> …
Since the other "parameter" is i, which has the same type as x, we end up with:
type X = (Integer -> Integer -> Integer) -> X -> …
which is an infinite type.
So the proper solution would be
primes remNum =
let i = head remNum
in i : primes (filter (\(x) -> x `mod` i /= 0) (tail remNum))
or
primes remNum =
let i = head remNum
in i : primes (filter (\(x) -> mod x i /= 0) (tail remNum))
or (with pattern matching)
primes (i:remNums) = x : primes (filter (\x -> mod x i /= 0) remNums)

Program to find the result of primitive recursive functions

I'm writing a program to solve the result of primitive recursive functions:
1 --Basic functions------------------------------
2
3 --Zero function
4 z :: Int -> Int
5 z = \_ -> 0
6
7 --Successor function
8 s :: Int -> Int
9 s = \x -> (x + 1)
10
11 --Identity/Projection function generator
12 idnm :: Int -> Int -> ([Int] -> Int)
13 idnm n m = \(x:xs) -> ((x:xs) !! (m-1))
14
15 --Constructors--------------------------------
16
17 --Composition constructor
18 cn :: ([Int] -> Int) -> [([Int] -> Int)] -> ([Int] -> Int)
19 cn f [] = \(x:xs) -> f
20 cn f (g:gs) = \(x:xs) -> (cn (f (g (x:xs))) gs)
these functions and constructors are defined here: http://en.wikipedia.org/wiki/Primitive_recursive_function
The issue is with my attempt to create the compositon constructor, cn. When it gets to the base case, f is no longer a partial application, but a result of the function. Yet the function expects a function as the first argument. How can I deal with this problem?
Thanks.
Given f,
f :: [a] -> b
and g_k,
g_k :: [a] -> a
we want to produce h,
h :: [a] -> b
so the composition should be like
compo :: ([a] -> b) -> [[a] -> a] -> [a] -> b
compo f gs xs = f (map ($ xs) gs)
Example: http://codepad.org/aGIKi8dF
Edit: It can also be written in applicative style (eliminating that $) as
compo f gs xs = f (gs <*> pure xs)

Unwrapping datatypes in Haskell without extraneous code

Say I have
x = Just 2
Is there a way (preferrably a builtin mechanism/function) to use x in a single statement such that if it is a Just, then the 2 is automatically unwrapped and used, and if it is a Nothing, an exception is raised?
That is,
(f x) + 2 == 4 if x == Just 2, and raises an exception if x == Nothing.
Data.Maybe.fromJust has been mentioned by other answers already:
fromJust :: Maybe a -> a
fromJust Nothing = error "Maybe.fromJust: Nothing"
fromJust (Just x) = x
There's also maybe (found in both Prelude and Data.Maybe):
maybe :: b -> (a -> b) -> Maybe a -> b
maybe n _ Nothing = n
maybe _ f (Just x) = f x
fromJust can be written using maybe:
fromJust = maybe (error "Maybe.fromJust: Nothing") id
As you can see, maybe allows you flexibility in handling both cases without requiring pattern matching:
\x -> maybe 0 (+ 2) x -- Nothing -> 0, Just 2 -> 4
Similarly, Prelude and Data.Either have either :: (a -> c) -> (b -> c) -> Either a b -> c:
\x -> either (subtract 1) (* 2) x -- Left 5 -> 4, Right 3 -> 6
If you define a data type
data MyDataType
= TypeA { foo :: Int, bar :: String }
| TypeB { foo :: Int, baz :: () }
| TypeC { bar :: String, baz :: () }
like this, you end up with partial functions for accessors.
foo :: MyDataType -> Int
bar :: MyDataType -> String
baz :: MyDataType -> ()
They're called partial functions, as opposed to total functions, because they only return results for a subset of their inputs.
foo (TypeA { foo = 15, bar = "hello!" }) -- 15
bar (TypeB { foo = 12345679, baz = () }) -- error
For this particular case, fromJust. In general
let Just k = x in f k + 2 == 4
This trick works with any datatype constructor and is very commonly used with (:) for nonempty lists.
fromJust should do what you want.

Resources