Haskell - Array - arrays

I'm a newbie to Haskell, got stuck on a simple question:
aaa :: [[(Char, Float)]] -> Float -> [[(Char, Float)]]
aaa [[]] a = error "no indata"
aaa [[(a,b)]] c = [[(a, b/c)]]
aaa inD c = ??
How to make it work with more than 1 element in Array?
Ex: aaa [[('a',3)],[('b',4)],[('c',5)]] 4
the result: [[('a',0.75)],[('b',1)],[('c',1.25)]]
Any hint pls, thx!

You can define operations on lists as follows (I give you a simpler example that adds 1 to each list item)
f [] = []
f (head:tail) = (head + 1):(f tail)
I.e. head:tail represents a list; to be more specific, it represents the first list item (head) and the remaining list if we take the first item away (tail). Then, you usually apply your stuff to head and make a recursive call using tail.
Completing your example (without testing) this would yield:
aaa ([(a,b)]:tail) c = [(a, b/c)] : (aaa tail c)
One thing: You are dealing with a list and want to modify each element of the list in a specific way (but each element is transformed the same way). For such occasions, Haskell provides its intrinsic map function, which takes:
the function to transform a list items
the list of items
as parameters and returns the transformed list.

First of all, that [...] stuff denotes lists, not arrays; there is a fundamental difference between those two.
Try to think in terms of fmap :: Functor a => (a -> b) -> f a -> f b. This function takes another function and applies it over a data-structure. You could use it to implement your function. Here is a simple implementation. Try to understand it:
aaa l c = fmap (fmap (fmap (/c))) l

Related

Check if a list is sorted or not in ml language

i want to write program that can checked a list is sorted or not in ml language program but i am new at this language
i write the below code and seems it works
is there any tips i can use in my ml programing
ml programming language
let issorted x = match x with
[] -> true
| _::[] -> true
| _::_ -> issorted_helper (x);;
let rec issorted_helper x = match x with
| [] -> true
| h::t ->
if h > t
false
else
issorted_helper(t);;
That code is not only in OCaml, it's also wrong, so there's little point in translating it.
Write down a case analysis on the structure of the list;
The empty list is sorted
A list with one element is sorted
A list with more than one element is sorted if its first two elements are in order, and the tail of the list is sorted.
Then you translate that to SML.

Function Recursion within itself - haskell

I was trying to recursively pass a function to itself a given number of times. So given the input in form of Function | RepeatNumber(Count) | Argument. So as an example if given the input: f 3 2 it would return f(f(f 2) This should then also work if the Function value where "square" it would Square the argument.
In terms of the logic I approached it as follows:
def repeatnew func count arg
if count == 1 then (func arg)
else (func (repeatnew func (count -1) arg))
I've been trying to research a solution to this for a while and I came across using Iterate and some other functions. Finally I came across this: https://wiki.haskell.org/Higher_order_function However I was unable to implement a working solution.
Edit: The solutions I did try to implement I could get compiling correctly, I am still very inexperienced with haskell and would appreciate an explanation on how to create a higher order function using my parameters.
Spinning off from #Antisthenes' comment, One other way to do this is using the foldl1 with no base case.
pipeNTimes :: (a -> a) -> Int -> (a -> a)
pipeNTimes f n = foldl1 (.) $ replicate n f
pipeNTimes (*2) 3 2 -- returns 16
I am admittedly only a beginner at Haskell, so this may be a naive implementation, but I think this does what you are looking for:
applyRecursively f x y
| x == 1 = f y
| otherwise = f (applyRecursively f (x-1) y)
The applyRecursively function takes a function and two numbers as arguments.
If the middle argument (the count) is 1 then we apply the parameter function to the argument y. This is the edge case that stops the recursion.
The otherwise guard clause then calls recursively with the x parameter decremented, and applies function f to the result.
I have tested it using a lambda like this:
applyRecursively (\x -> x + 1) 3 3
It should add 1 to the values of 3 three times - it returns a value of 6 so it looks like it works.
As I say, I'm a beginner but I think this does what you're looking for.

Sort Arrays in Array in Lua

Hi i am quite new to lua and i need to sort an Array in Lua.
So i have following code
local distances = {2,3,1}
table.sort(distances)
now i get
distances[1] -> 1
distances[2] -> 2
distances[3] -> 3
now i need to save some information for my "distances" aswell
something like the following
local distances = {{C1,2},{C2,3},{C3,1}}
now it is impossible to call the sort-function, but i need them sorted.
Is it possible to reach this?
distances[1] -> {C3,1}
distances[2] -> {C2,2}
distances[3] -> {C1,3}
Thanks guys :)
table.sort takes a comparison function as its second argument.
table.sort(distances, function (left, right)
return left[2] < right[2]
end)

Haskell iteration (not literally) over a list

I know I should be forgetting about iterating in functional languages, but I dont know how else to put forth my question.
If I have a list of integers arranged in ascending or descending order, and I have an arbitrary number that may or may not be present in the list, how can I loop over the list to find a number that is small than the given number and return that integer.
I just need to know how to go about it.
You could use find to find the first element matching a predicate you specify. Example:
find even [3,5,7,6,2,3,4]
Or, you could drop all the unwanted elements from the left:
dropWhile (not . even) [3,5,7,6,2,3,4]
(and possibly take the first element remaining, which has to be even).
Or, you could filter out unwanted elements
filter even [3,5,7,6,2,3,4]
Or, you could use recursion and code everything yourself.
You can recursively deconstruct the list with pattern matching:
searchList :: Int -> [Int] -> ???
searchList n [] = ???
searchList n (x:xs) = ???
You check whether x is the number you want, and if not you can call searchList n xs to search the rest of the list.
The normal way to do something like that would be with the library function foldr, but it would be better to understand how to do this with recursion first.
You can have "state" in a list iteration by using a fold - the state is passed from one iteration to the next in a function argument.
An example:
sup :: [Int] -> Int -> Int
sup xs y = go (head xs) xs
where
go s [] = s
go s (x:xs) = if x >= y then s else go x xs
Here s is the "state" -- it is the latest value in the list that is less than y.
Because you said the input list would never be empty, head xs is okay here.
This is almost what you want. Perhaps you can modify it to handle all of your conditions.

haskell repeat all chars in a string

i just started with Haskell and wanted to do a little function that takes an integer and a String to repeat each char in the String as often as the integer implies.
e.g.: multiply 3 "hello" would output "hhheeelllooo"
My problem now is that i am not sure how to iterate over all the chars.
multiply::Int->String->String
multiply 1 s = s
multiply i s = multiply (i-1) (take 1 s ++ s)
so what i would get is "hhhello". so basically i need to do something like:
mult::Int->String->String
mult 0 s = []
mult 1 s = s
mult i s = "iterate over s, take each char and call a modified version of the multiply method that only takes chars above"
Thank you for helping me out
This gets easier when you use the standard library. First off, repeating an item is done with replicate:
Prelude> replicate 3 'h'
"hhh"
You can then partially apply this function and map it over the string:
Prelude> map (replicate 3) "hello"
["hhh", "eee", "lll", "lll", "ooo"]
And finally concat that list of strings into one string:
Prelude> concat (map (replicate 3) "hello")
"hhheeellllllooo"
The composition of concat and map can be abbreviated as concatMap (this is a library function, not a language feature).
Prelude> concatMap (replicate 3) "hello"
"hhheeellllllooo"
So your function becomes
mult n s = concatMap (replicate n) s
For extra brevity, write this in point-free style as
mult = concatMap . replicate
There are many ways to achieve the same effect as you would with a loop in other languages, and larsmans has shown you one way, using map. Another common way is with recursion. You already know what to do with the first character, so you can recurse through the list like so:
multiply n [] = []
multiply n (x:xs) = replicate n x ++ multiply n xs
larsmans has explained how replicate works. For your homework, maybe you're not supposed to use library functions like replicate, so you can replace the call to replicate with your own version.
Another way based on monadic's nature of list.
You'd like to apply a function to each element of a list.
To do this just bind the list to the function, like this
# "hello" >>= replicate 3
Or,
# let f = flip (>>=) . replicate
To remove flip,
# let g = (=<<) . replicate
You can use applicative functors for this:
import Control.Applicative
multiply n = (<* [1..n])
--- multiply 3 "hello" --> "hhheeellllllooo"

Resources