Check if a list is sorted or not in ml language - ml

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.

Related

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)

Turning a list of Integers into a List of Colors

I have an image stored as a very large List Int and I would like to turn them into a List Color However remember that rgb requires 3 arguments and rgba requires 4. So let's try:
toColor : List Int -> List Color
toColor x =
if List.isEmpty x then
[]
else
List.append ( rgba <| List.take 4 x ) ( toColor <| List.drop 4 x )
This definition is recursive. We chomp 4 numbers, create an rgb color and append the results. However if x is List Int we cannot write this:
rgba <| List.take 4 x
Here is the kind of error we get. rgb is expecting three numbers and instead it gets a list
71| rgb <| List.take 4 x
^^^^^^^^^^^^^
(<|) is expecting the right argument to be a:
Int
But the right argument is:
List a
I wonder that taking out the first element of a List Int returns a Maybe Int
head : List a -> Maybe a
> head [1,2,3,4]
Just 1 : Maybe.Maybe number
Here is a modification of rgb which turns 3 Maybe Int into a Color. Now, reading the image data, I think rgba is necessary but I just add one more.
rgb' : Maybe Int -> Maybe Int -> Maybe Int -> Color
rgb' a b c =
case a of
Nothing -> rgb 0 0 0
Just a' -> case b of
Nothing -> rgb 0 0 0
Just b' -> case c of
Nothing -> rgb 0 0 0
Just c' -> rgb a' b' c'
this started when I was translating this d3js example to Elm and I noticed it used some features which aren't currently supported in Elm. In particular ctx.getImageData() since you can't import and image to Canvas. So this is part of my make-shift solution.
It seems to me that you're looking for a really clean way to
Collapse a List Int into a List (List Int), where each child list has at most 3 or 4 members if you want to do rgb or rgba.
Pass each List Int into a function that will convert it using rgb, handling the case where there aren't enough Ints in the final entry.
For the first step, you can write a function called groupList:
groupsOf : Int -> List a -> List (List a)
groupsOf size list =
let
group =
List.take size list
rest =
List.drop size list
in
if List.length group > 0 then
group :: groupsOf size rest
else
[]
You can also get this functionality by using the greedyGroupsOf function from the elm-community/list-extra package.
For the second step, it'll be much cleaner to pattern match on the structure of the list value itself rather than using List.head and matching on Maybe.
rgbFromList : List Int -> Color
rgbFromList values =
case values of
r::g::b::[] ->
rgb r g b
_ ->
rgb 0 0 0
The first case will be matched when there are exactly 3 entries in the list, and everything else will fall through to handing 0s to rgb.
You can put all of these things together by doing the following:
toColor : List Int -> List Color
toColor x =
x
|> groupsOf 3
|> List.map rgbFromList
Alternatively, if instead of ending up with rgb 0 0 0 for invalid colors you want to exclude them entirely, you can use the List.filterMap function to prune out things you don't want. We can change rgbFromList to look like
rgbFromList : List Int -> Maybe Color
rgbFromList values =
case values of
r::g::b::[] ->
Just <| rgb r g b
_ ->
Nothing
and then call it like
toColor : List Int -> List Color
toColor x =
x
|> groupsOf 3
|> List.filterMap rgbFromList
Please be advised that since the groupsOf function here as well as greedyGroupsOf in elm-community/list-extra is recursive, it will fail for very large lists.
Edit: for very large lists
For very large lists it's easy to get into trouble with recursion. Your best bet is to fold over the list and manage some intermediate state while you're folding:
groupsOf : Int -> List a -> List (List a)
groupsOf size list =
let
update next state =
if (List.length state.current) == size then
{ current = [next], output = state.current :: state.output }
else
{ state | current = state.current ++ [next] }
result =
List.foldl update { current = [], output = [] } list
in
List.reverse (result.current :: result.output)
This works by folding over the list, which is an iterative process rather than recursive, and building up groups one at a time. The last step reverses the list because it will be constructed in reverse order in order to cons instead of doing costly appends once the output list begins to grow large. I don't expect this to overflow the stack, but it is likely that it will be very slow. In my opinion, your best option to get the outcome you are looking for in a reasonable amount of time is to write the groupsOf function in JavaScript using a for loop and then pass the result in through a port.
This recursive implementation should work without building the stack, because Elm has tail call optimisation. Each step takes three ints from the original list, and appends them to the list of colors. Recursion stops and returns the list of colors, when there are less than three elements in the original list.
It uses rgb, but can be easily modified to take 4 elements from the list.
It also reverses the order, so you might need to combine it with List.reverse.
import Color exposing (rgb, Color)
listColors : List Int -> List Color
listColors =
listColors' []
listColors' : List Color -> List Int -> List Color
listColors' colors ints =
case ints of
r :: g :: b :: rest ->
listColors' (rgb r g b :: colors) rest
_ ->
colors

Array vs List in Elm

I was suprised to learn that Array and List were two different types in Elm:
Array
List
In my case, I have a List Int of length 2,000,000 and I need about 10,000 of them but I don't know in advance which ten thousand. That will be provided by another list. In pseudo-code:
x = [ 1,1,0,30,...,255,0,1 ]
y = [ 1,4,7,18,36,..., 1334823 , ... 1899876 ]
z = [ y[x[0]], y[x[1]], ... ]
I am using pseudocode because clearly this isn't Elm syntax (it might be legal JavaScript).
Can these array selections be done in List or Array or both?
List is a linked list which provides O(n) lookup time based on index. Getting an element by index requires traversing the list over n nodes. An index lookup function for List isn't available in the core library but you can use the elm-community/list-extra package which provides two functions for lookup (varying by parameter order): !! and getAt.
Array allows for O(log n) index lookup. Index lookups on Array can be done using Array.get. Arrays are represented as Relaxed Radix Balanced Trees.
Both are immutable (all values in Elm are immutable), so you have trade-offs depending on your situation. List is great when you make a lot of changes because you are merely updating linked list pointers, whereas Array is great for speedy lookup but has somewhat poorer performance for modifications, which you'll want to consider if you're making a lot of changes.
Something like this should work:
import Array
import Debug
fromJust : Maybe a -> a
fromJust x = case x of
Just y -> y
Nothing -> Debug.crash "error: fromJust Nothing"
selectFromList : List a -> List Int -> List a
selectFromList els idxs =
let arr = Array.fromList els
in List.map (\i -> fromJust (Array.get i arr)) idxs
It converts the input list to an array for fast indexing, then maps the list of indices to their corresponding values in the array. I took the fromJust function from this StackOverflow question.
Only use Array if you need to use Array.get.
In most cases you should use List because usually you can do everything you need with foldl, map, etc. without having to get items from an index, and List has better performance with these functions.

Non-monolithic arrays in Haskell

I have accepted an answer to the question below, but It seemed I misunderstood how Arrays in haskell worked. I thought they were just beefed up lists. Keep that in mind when reading the question below.
I've found that monolithic arrays in haskell are quite inefficient when using them for larger arrays.
I haven't been able to find a non-monolithic implementation of arrays in haskell. What I need is O(1) time look up on a multidimensional array.
Is there an implementation of of arrays that supports this?
EDIT: I seem to have misunderstood the term monolithic. The problem is that it seems like the arrays in haskell treats an array like a list. I might be wrong though.
EDIT2: Short example of inefficient code:
fibArray n = a where
bnds = (0,n)
a = array bnds [ (i, f i) | i <- range bnds ]
f 0 = 0
f 1 = 1
f i = a!(i-1) + a!(i-2)
this is an array of length n+1 where the i'th field holds the i'th fibonacci number. But since arrays in haskell has O(n) time lookup, it takes O(n²) time to compute.
You're confusing linked lists in Haskell with arrays.
Linked lists are the data types that use the following syntax:
[1,2,3,5]
defined as:
data [a] = [] | a : [a]
These are classical recursive data types, supporting O(n) indexing and O(1) prepend.
If you're looking for multidimensional data with O(1) lookup, instead you should use a true array or matrix data structure. Good candidates are:
Repa - fast, parallel, multidimensional arrays -- (Tutorial)
Vector - An efficient implementation of Int-indexed arrays (both mutable and immutable), with a powerful loop optimisation framework . (Tutorial)
HMatrix - Purely functional interface to basic linear algebra and other numerical computations, internally implemented using GSL, BLAS and LAPACK.
Arrays have O(1) indexing. The problem is that each element is calculated lazily. So this is what happens when you run this in ghci:
*Main> :set +s
*Main> let t = 100000
(0.00 secs, 556576 bytes)
*Main> let a = fibArray t
Loading package array-0.4.0.0 ... linking ... done.
(0.01 secs, 1033640 bytes)
*Main> a!t -- result omitted
(1.51 secs, 570473504 bytes)
*Main> a!t -- result omitted
(0.17 secs, 17954296 bytes)
*Main>
Note that lookup is very fast, after it's already been looked up once. The array function creates an array of pointers to thunks that will eventually be calculated to produce a value. The first time you evaluate a value, you pay this cost. Here are a first few expansions of the thunk for evaluating a!t:
a!t -> a!(t-1)+a!(t-2)-> a!(t-2)+a!(t-3)+a!(t-2) -> a!(t-3)+a!(t-4)+a!(t-3)+a!(t-2)
It's not the cost of the calculations per se that's expensive, rather it's the need to create and traverse this very large thunk.
I tried strictifying the values in the list passed to array, but that seemed to result in an endless loop.
One common way around this is to use a mutable array, such as an STArray. The elements can be updated as they're available during the array creation, and the end result is frozen and returned. In the vector package, the create and constructN functions provide easy ways to do this.
-- constructN :: Unbox a => Int -> (Vector a -> a) -> Vector a
import qualified Data.Vector.Unboxed as V
import Data.Int
fibVec :: Int -> V.Vector Int64
fibVec n = V.constructN (n+1) c
where
c v | V.length v == 0 = 0
c v | V.length v == 1 = 1
c v | V.length v == 2 = 1
c v = let len = V.length v
in v V.! (len-1) + v V.! (len-2)
BUT, the fibVec function only works with unboxed vectors. Regular vectors (and arrays) aren't strict enough, leading back to the same problem you've already found. And unfortunately there isn't an Unboxed instance for Integer, so if you need unbounded integer types (this fibVec has already overflowed in this test) you're stuck with creating a mutable array in IO or ST to enable the necessary strictness.
Referring specifically to your fibArray example, try this and see if it speeds things up a bit:
-- gradually calculate m-th item in steps of k
-- to prevent STACK OVERFLOW , etc
gradualth m k arr
| m <= v = pre `seq` arr!m
where
pre = foldl1 (\a b-> a `seq` arr!b) [u,u+k..m]
(u,v) = bounds arr
For me, for let a=fibArray 50000, gradualth 50000 10 aran at 0.65 run time of just calling a!50000 right away.

Haskell - Array

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

Resources